对于任何好的反应,我试图将我的组件注入服务,但我获得了一个新的实例.我用这段代码重现了我的问题:
该组件将在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) { } }
我正在使用angular-cli,我的app.module.ts看起来:
@NgModule({ declarations: [ AppComponent,MyComponent ],imports: [ BrowserModule,],providers: [MyComponent,MyService],bootstrap: [AppComponent] }) export class AppModule { }
目前,我的控制台显示实例编号0,而我的html显示实例编号1.
我怎样才能获得相同的实例?
谢谢你读我
解决方法
这不起作用.如果您的应用程序具有此组件的多个实例,则应注入哪个实例.
您可以做的是例如将服务注入组件并使组件自己传递给服务
@Component({ selector: 'my-component',template: '<h1>Instance number {{count}}</h1>' }) export class MyComponent { constructor(service: MyService) { service.myComponent = this; } private static i = 0; private _count: number = i++; get count(): number {return this._count} }
最好不要将组件传递给服务,而是使用observable来通知组件有关事件的信息,让组件完成剩下的工作.
有关详细信息,请参阅https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service