2017-04-18 71 views
0

我在其他組件(父級)內部有一個組件(子級)。這個標籤叫做router-outlet。 我寫了一個服務,以便孩子可以改變父母的變量,因爲在這種情況下,我不能使用EventEmitterOutput,但它不起作用。沒有通過Angular 2中的服務更新

服務:

import {Subject} from 'rxjs/Subject'; 

import {Injectable} from '@angular/core'; 

@Injectable() 
export class TabStatusService { 


    private sub=new Subject<boolean>(); 
    dataStatus$ = this.sub.asObservable(); 

    changeStatus(data:boolean){ 

    this.sub.next(data); 
    } 
} 

父:

@Component({ 
    ... 
    providers:[TabStatusService] 
}) 


export class SecondarytabsComponent implements OnInit { 


private status:boolean=false; 
    constructor(private tabStatusService: TabStatusService) { 


    ngOnInit() { 


    this.tabStatusService.dataStatus$.subscribe(
     data => { 
     this.status = data; 

     }); 
    } 
} 

模板:

<div> 



    <p>{{status}} </p> 


</div> 
<router-outlet></router-outlet> 

孩子:

@Component({ 
    .... 
    providers:[ConfirmationService, TabStatusService] 
}) 
export class ProceduresComponent implements OnInit { 

    constructor(private confirmationService: ConfirmationService, private tabStatusService:TabStatusService) { 


    } 

    ngOnInit() { 
    } 

    setStatus(value){ 
    this.tabStatusService.changeStatus(value); 
    } 

} 

模板:

<div> 

<button type="button" class="btn btn-primary btn-lg btn-block login-button"(click)="setStatus(true)">Back</button> 

</div> 

問題在哪裏?

謝謝

+0

「不起作用」不是問題描述。你有什麼努力使它工作? –

+0

我會點擊子按鈕,父母的「狀態」變量從false更改爲true。 – dstyle

+0

爲什麼你在每個組件上都有提供者:[TabStatusService]? – zeroflagL

回答

0

從你的孩子組成的providers元屬性字段刪除[TabStatusService]

當前您創建同一服務的多個實例。您需要爲其提供根組件或@NgModule以共享相同的服務實例。

如果你這樣做,它應該按預期工作。

+0

謝謝,現在的作品! – dstyle

+0

@dstyle很好,如果能爲您解決問題,請您接受答案。謝謝。 – unitario