1
我有一個組件和一個服務。每當我的服務中的布爾屬性發生更改時,我都想通知我的組件。我想我應該使用rxjs中的Observable和Observer。監視angular2中服務和更新組件的更改,打印稿
我做了服務和組件不按預期工作。
AppComponent.ts
import { Component } from '@angular/core';
import { UserData } from 'user-data.service';
@Component({
selector: 'app',
templateUrl: '<div></div>'
})
export class AppComponent {
isLoggedIn: boolean;
constructor(public userData: UserData) {
userData.isLoggedIn.subscribe(isLoggedIn => {
this.isLoggedIn = isLoggedIn;
});//???
}
???
}
UserDataService.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class UserData {
isLoggedIn: Observable<boolean>; // ???
observer: Observer<boolean>; // ??? giving an error in tsc (Type 'Observer' is not generic)
constructor() {
this.isLoggedIn = new Observable(observer =>
this.observer = observer
).share(); ///???
}
changeLoginStatus (isLoggedIn: boolean) { // function called from login/logout actions
this.observer.next(isLoggedIn); // ??? not sure
}
}
下一個方法是在Observer類型上,而不是在Observable上 – lintu
對不起,請將類型更改爲'Subject'。 –
當我嘗試使用新的BehaviorSubject(false);我在rxjs上獲得了404。 http:// localhost:8080/node_modules/rxjs/404(Not Found)。但我可以使用rxjs中的'Subject'。 從'rxjs'導入{BehaviorSubject};從'rxjs/Subject'導入{Subject}時拋出錯誤;作品。任何想法?? – lintu