我在其他組件(父級)內部有一個組件(子級)。這個標籤叫做router-outlet
。 我寫了一個服務,以便孩子可以改變父母的變量,因爲在這種情況下,我不能使用EventEmitter
和Output
,但它不起作用。沒有通過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>
問題在哪裏?
謝謝
「不起作用」不是問題描述。你有什麼努力使它工作? –
我會點擊子按鈕,父母的「狀態」變量從false更改爲true。 – dstyle
爲什麼你在每個組件上都有提供者:[TabStatusService]? – zeroflagL