對於任何好的重做,我試圖將我的組件注入到服務中,但是我獲得了它的一個新實例。我重現我的問題與此代碼:注入服務中的組件實例
此組件將在h1
顯示實例編號:
@Component({
selector: 'my-component',
template: '<h1>Instance number {{count}}</h1>'
})
export class MyComponent {
private static i = 0; /* <-- counts the myComponent's instances here */
private _count: number = i++;
get count(): number {return this._count}
}
該服務將登錄控制檯實例編號:
@Injectable()
export class MyService {
constructor(myComponent: MyComponent) {
console.log("Instance number " + myComponent.count);
}
}
主要成分會在視圖和服務中注入組件:
@Component({
selector: 'app-root',
template: '<my-component></my-component>',
})
export class AppComponent {
constructor(service: MyService) {
}
}
我使用角CLI,我app.module.ts樣子:
@NgModule({
declarations: [
AppComponent,
MyComponent
],
imports: [
BrowserModule,
],
providers: [MyComponent, MyService],
bootstrap: [AppComponent]
})
export class AppModule { }
目前,我的控制檯顯示Instance number 0
和我的HTML顯示Instance number 1
。 我如何獲得相同的實例?
感謝您的閱讀
感謝您的反應答案!我正在閱讀... –