说我有这个服务和组件。我想使用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;
}
}
由于我收到此错误,因此无法编译:
有没有办法使用方法而不是构造函数来注入服务的新实例?
所述喷油器服务可以用来使用一种方法以注入服务:
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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句