【发布时间】:2018-02-01 19:52:59
【问题描述】:
假设我有这个服务和组件。我想使用多个 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;
}
}
这将无法编译,因为我收到此错误:
有没有办法使用方法而不是构造函数来注入服务的新实例?
【问题讨论】:
-
尝试这个的原因是什么?您的 MySillyService 实例是否在运行时发生变化?
-
我想注入多个 MySillyService 实例,我不想重复使用同一个实例。有意义吗?
-
@ConnorsFan 有正确的想法