2016-12-01 64 views
2

對於任何好的重做,我試圖將我的組件注入到服務中,但是我獲得了它的一個新實例。我重現我的問題與此代碼:注入服務中的組件實例

此組件將在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。 我如何獲得相同的實例?

感謝您的閱讀

回答

4

這是行不通的。如果你的應用程序有這個組件的多個實例,它應該注入哪個實例。

你可以做的是例如注入的服務組件,使組件通過自身的服務

@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} 
} 

最好是不通過組件服務,而是使用觀測通知有關組件事件並讓組件完成剩下的工作。

欲瞭解更多詳情,請參閱https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

+0

感謝您的反應答案!我正在閱讀... –

2

謝謝您的回答@君特。我在這裏發佈我訂購了服務的新組件對任何人感興趣:

可觀察到的服務:

@Injectable() 
export class MyService implements OnDestroy { 
    private _count:number = 0; 
    public numberSource = new Subject<number>(); 
    private numberObservable: Observable<number> = this.numberSource.asObservable().share(); 

    public count() {this.numberSource.next(this._count++);} 
    public subscribe(s: any) {return this.numberObservable.subscribe(s);} 
    public ngOnDestroy() {this.numberSource.complete();} 
} 

一個subcriber組件(我可以有很多):

@Component({ 
    selector: 'my-component', 
    template: ` 
<button (click)="increment()" >Count !</button> 
<div *ngFor="let n of numbers">{{n}}</div> 
` 
}) 
export class MyComponent { 
    private numbers: number[] = []; 
    constructor(private myService: MyService) { 
     myService.subscribe((n:number) => this.numbers.push(n)); 
    } 
    increment() { 
     this.myService.count(); 
    } 
} 

我不知道我是否清楚,但這正是我所期待的。謝謝 !

相關問題