在使用angular的工厂提供程序并在factory.service.ts中发送两个参数之后,我想显示“factory”和一个布尔值。
它似乎在其他Angular 版本中工作得很好,但在Angular 15版本中出现了一个问题。
我不知道问题出在哪...
home.component.ts
import { Component, Inject, OnInit } from '@angular/core';
import { FactoryService } from '../factory.service';
import { LogService } from '../log.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [LogService,
{provide: 'another', useClass: LogService},
{provide: 'same',useExisting: LogService},
{provide: 'githubUrl',useValue: 'https://github.com/abcd'},
{provide: 'factory',useFactory: (logService) => {
return new FactoryService(logService, true);},
deps: [FactoryService]
}]
})
export class HomeComponent implements OnInit{
constructor(private log:LogService,
@Inject('another') private another,
@Inject('same') private same,
@Inject('githubUrl') private url,
@Inject('factory') private factory
) {
console.log("this.log === this.another", this.log === this.another)
console.log("this.log === this.same", this.log === this.same)
console.log(this.url)
}
ngOnInit(): void {
this.log.info('logservice');
this.factory.log();
}
}
factory.service.ts
import { Inject, Injectable } from "@angular/core";
import { LogService } from "./log.service";
@Injectable()
export class FactoryService {
constructor(private logService: LogService, private isFactory: boolean) {}
public log() {
this.logService.info(`factory ${this.isFactory}`);
}
}
错误
Error: src/app/factory.service.ts:6:57 - error NG2003: No suitable injection token for parameter 'isFactory' of class 'FactoryService'.
Consider using the @Inject decorator to specify an injection token.
6 constructor(private logService: LogService, private isFactory: boolean) {}
~~~~~~~~~
src/app/factory.service.ts:6:68
6 constructor(private logService: LogService, private isFactory: boolean) {}
~~~~~~~
This type is not supported as injection token.
我看过官方文件,但我不知道问题出在哪里。
2条答案
按热度按时间hwamh0ep1#
根据错误消息的建议,您应该为自定义参数使用
@Inject
装饰器,否则Angular会将其视为依赖项并尝试解决它。由于您没有这样的
isFactory
提供程序,Angular 抛出错误。添加名为
isFactory
的@Inject装饰器工厂.服务.ts
提供
isFactory
值并删除new FactoryService
中的第二个参数主组件ts
未测试代码。
有关详细信息,请参阅https://www.positronx.io/how-to-pass-parameters-to-angular-service-using-inject/。
jogvjijk2#
最简单的解决方法是使用注入令牌。如果使用
factory
,则这些令牌是树可摇动的。为了提供,
如果您想在具有类型安全的组件中使用
inject
的第二个参数允许使用optional、self、host等常用分辨率修饰符。