【发布时间】:2017-04-16 05:04:26
【问题描述】:
出于任何好的原因,我正在尝试将我的组件注入到服务中,但我获得了它的一个新实例。我用这段代码重现了我的问题:
该组件将在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}
}
Service会在控制台中记录实例号:
@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) {
}
}
我正在使用 angular-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。
如何获取相同的实例?
感谢阅读
【问题讨论】: