假设我有这个服务和组件。我想使用 MySillyService 的多个实例。
@Injectable()
export class MySillyService {
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
vals: Array<MySillyService>;
constructor() {
this.vals = [1,2,3].map(v => {
return this.getSillyService();
});
}
@Inject(MySillyService)
getSillyService(mss: MySillyService){
console.log('getting mss...');
return mss;
}
}
这不会编译,因为我收到此错误:
有没有办法使用方法而不是构造函数来注入(inject)服务的新实例?
最佳答案
Injector service 可用于使用方法注入(inject)服务:
import { Injector } from '@angular/core';
export class AppComponent {
vals: Array<MySillyService>;
mySillyService: MySillyService;
constructor(private injector: Injector) {
this.vals = ['some','dynamic','array'].map(v => this.getSillyService());
}
getSillyService() {
return this.injector.get(MySillyService);
}
injectAnotherInstance() {
this.mySillyService = this.injector.get(MySillyService);
}
}
关于angular - 使用方法而不是构造函数注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48570692/