2017-05-24 87 views
1

有沒有開始從可觀察到的發光有條件值的方法?在我的情況下,.asObservable()函數的用戶只能在CurrentUser初始化後獲得第一個值。可觀察 - 開始發出有條件

export class CurrentUser { 

    private currentUser$: Observable<CurrentUser>; 
    private currentUserBehaviorSubject: BehaviorSubject<CurrentUser>; 

    public name: string = ""; 

    constructor() { 
     this.currentUserBehaviorSubject = new BehaviorSubject(this); 
     this.currentUser$ = this.currentUserBehaviorSubject.asObservable(); 
    } 

    public asObservable(): Observable<CurrentUser> { 
     // 
     if(user.name.length > 0){ 
      return this.currentUser$; 
     } 
     else { 
      // ????? 
     } 
    } 

    public initialize(string name){ 
     this.name = name; 
     this.currentUserBehaviorSubject.next(this); 
    } 
} 

export class SampleComponent { 
    constructor(
     currentUser: CurrentUser 
    ) { 
     currentUser.asObservable().subscribe(
      (u: CurrentUser) => { 
       // i only want an INITIALIZED user here 
      }, 
      error => {}, 
      () => { } 
     ); 
    } 
} 
+0

誰初始化示例組件 –

回答

3

它看起來像你可以在你的asObservable()方法總是返回可觀察到的,只是抑制使用skipUntil()運營商的排放,直到currentUserBehaviorSubject發出(我想這是CurrentUser你如何知道已被初始化):

public asObservable(): Observable<CurrentUser> { 
    return this.currentUser$ 
     .skipUntil(this.currentUserBehaviorSubject); 
} 
0

我怎麼看到:

export class CurrentUser { 
    subject: Subject<CurrentUser> = new Subject<CurrentUser>(); 
    observable: Observable<CurrentUser = this.subject.asObservable(); 

    constructor() { 
     // Do your business 
     this.subject.next(this); 
    } 
} 

而在你的組件,只需訂閱observable p roperty。

這樣,當你初始化一個新的CurrentUser時,你的觀察者會被通知。這是你想要的,還是我誤解了?