2016-12-02 71 views
0

我在我的angular2應用程序中有可觀察的數據。該數據具有2個屬性在訂閱條件內執行代碼

{isFetching: false, user: {userID: 1, firstName: "john", lastName: "public"} }. 

當數據正從服務器isFetching標誌檢索爲真和用戶對象爲空。在我的組件之一中,我需要通過位於可觀察對象上的userID獲取一些其他數據。當observable訂閱的用戶對象爲null時。在我的代碼中,我必須在執行其他操作之前檢查用戶是否爲空。下面的代碼工作,但我認爲有更好的方式比有條件裏面的訂閱塊。

this.store.select<UserProfileState>('user') 
     .subscribe(user => { 
      if (!user.isFetching) { 
       this.store.dispatch(this.informationPanelActions.loadInformationPanel(user.user.clientID, user.user.userID)); 
      } 
     }); 

任何幫助表示讚賞。

回答

3

當你與一個可觀察的工作,你可以使用過濾器:

this.store.select<UserProfileState>('user') 
    .filter(user => !user.isFetching) 
    .subscribe(user => { 
     this.store.dispatch(this.informationPanelActions.loadInformationPanel(user.user.clientID, user.user.userID)); 
    }); 
+0

謝謝你,成功了! – Yousuf