2016-03-28 93 views
12

我有一個關於變化檢測的簡單問題。Angular 2組件聽着服務中的變化

我有一個組件和一個布爾內部的(全局)服務。 如何讓組件偵聽該布爾值並在該布爾變化時執行一個函數?

謝謝!

+2

見https://angular.io/docs/ts/latest/cookbook/component-communication.html #!#雙向服務 –

+0

酷感謝提示! –

+0

@MarkRajcok感謝分享! Angular 2的文檔真的出現了......我不知道他們在那裏有這樣的例子。 –

回答

17

根據布爾更改的方式,您可以在服務上將其公開爲Observable<boolean>,然後在組件中訂閱該流。你的服務看起來是這樣的:

@Injectable() 
export class MyBooleanService { 
    myBool$: Observable<boolean>; 

    private boolSubject: Subject<boolean>; 

    constructor() { 
     this.boolSubject = new Subject<boolean>(); 
     this.myBool$ = this.boolSubject.asObservable(); 
    } 

    ...some code that emits new values using this.boolSubject... 
} 

然後在你的組件,你會有這樣的事情:

@Component({...}) 
export class MyComponent { 
    currentBool: boolean; 

    constructor(service: MyBooleanService) { 
     service.myBool$.subscribe((newBool: boolean) => { this.currentBool = newBool; }); 
    } 
} 

現在取決於你需要與布爾值做什麼,你可能需要做一些其他的東西讓你的組件更新,但這是使用observable的要點。

另一種選擇是在模板中使用異步管道,而不是顯式訂閱構造函數中的流。同樣,這取決於你需要用bool值做什麼。

+0

非常感謝您的幫助! –

+2

你可以從rxjs主題 –

+0

** ** UserService.ts' this._dataService.get (this._userUrl) .subscribe(用戶=> { self.user = Enumerable.from(用戶).firstOrDefault( E => e.Email ==用戶名密碼&& == 「1234」);如果 (!! self.user){ self._isLoggedInSubject.next(TRUE);} });' **組件** 'isLoggedIn:boolean; 構造函數(private _userService:UserService){ this._userService.isLoggedIn.subscribe((response:boolean)=> this.isLoggedIn = response); }' 沒有爲我工作 – nadav

10

山姆的回答是完全正確的。我只想補充一點,你也可以利用一個打字稿二傳手自動觸發更改事件:

@Injectable() 
export class MyBooleanService { 
    myBool$: Observable<boolean>; 

    private boolSubject: Subject<boolean>; 

    constructor() { 
     this.boolSubject = new Subject<boolean>(); 
     this.myBool$ = this.boolSubject.asObservable(); 
    } 

    set myBool(newValue) { 
     this._myBool = newValue; 
     this.boolSubject.next(newValue); 
    } 
} 
+4

嗨,'this._myBool'從哪裏來?不知道對不起 – Lloople

+0

它應該是一個私人布爾服務,他只是忘了把它包括在他的示例代碼。 –