有几个类,如何注入TermsExchangeService
:
import {TermsExchangeService} from './terms-exchange.service';
@injectable()
export class TermsExchangeComponent {
constructor(
private termsExchangeService: TermsExchangeService
) {}
}
和
import {TermsExchangeService} from './terms-exchange.service';
@injectable()
export class PurchaseMainComponent {
constructor(
private termsExchangeService: TermsExchangeService
) {}
以及如何在PurchaseMainComponent
和TermsExchangeComponent
中使用
@injectable()
export class TermsExchangeService {
constructor() {
debugger; // call 2 times!!!
}
}
我使用autoBindInjectable
:
var simpleContainer = new Container({ autoBindInjectable: true })
从TermsExchangeService
的循环构造函数获取组件时,需要多次调用:
for (let item = 0; item < components.length; item++) {
const container = simpleContainer.get(components[item]);
}
为什么在每个组件中创建对象?以及如何进行正常注射?
答案 0 :(得分:0)
默认情况下,injectable
不是Singleton。
解决此问题可以添加defaultScope: 'Singleton'
:
var simpleContainer = new Container(
{
autoBindInjectable: true,
defaultScope: 'Singleton'
}
)