По какой-то причине я пытаюсь внедрить свой компонент в службу, но получаю его новый экземпляр. Я воспроизвожу свою проблему с этим кодом:
Этот компонент будет отображать номер экземпляра в 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 { }
В настоящее время моя консоль отображает Instance number 0
, а мой HTML-дисплей Instance number 1
. Как я могу получить тот же экземпляр?
Спасибо, что читаете меня