要跟蹤名稱屬性的更改,您必須使用observables。 更改您的服務如下。
主頁服務:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class HomeService {
private nameSource = new Subject<any>();
name$ = this.nameSource.asObservable();
setParams(val) {
this.nameSource.next(val);
}
}
在要改變名稱的成分B,它始終保持訂閱了服務的名稱。因此,無論何時在服務中更改名稱(當您爲組件A設置名稱時),您都可以跟蹤更改,並且組件B將得到更新。
以componentB:
import { Component, OnInit, OnDestroy} from '@angular/core';
import 'rxjs/add/operator/takeWhile';
import { HomeService } from '[add path of home service here]';
export class ComponentBComponent implements OnInit, OnDestroy{
private alive: boolean = true;
private name: string;
constructor(
private homeService: HomeService;
) {
homeService.name$.takeWhile(() => this.alive).subscribe(
name=> {
this.name = name;
});
}
ngOnInit() {
// Whatever to happen OnInit
}
ngOnDestroy() {
this.alive = false;
}
}
請注意takeWhile()
和alive
用於prevent memory leaks.
無論從任何地方你的名字設置爲主頁服務,
this.homeService.setParams(name);
這解決方案應該爲你工作。
我已經添加了一個答案來實現您的需要。請看看它。你必須使用observable來獲得這個工作,所以它訂閱param,並且每當做出更改時,它都會更新組件 –