2017-04-22 55 views
0

如果url參數不包含空ID,則調用getUserDetails和getOrganinztion List。 如果url參數不包含id,只需調用getOrganinztion。 但問題是結合最新不會調用方案2RxJs Partion if then else

let [updateUser$, createUser$] = this.route.params 
      .map((params: Params) => params['id']) 
      .partition(id => !!id); 


    updateUser$ = updateUser$ 
     .do(() => { 
     this.isEdit = true; 
     }) 
     .flatMap(id => this.userService.getUserById(id)) 
     .map(user => { 

     let languageId = user['languageId']; 
     let organization = user['organization']; 
     let organizationObj = [{ id: organization, text: organization }]; 
     return Object.assign(user, { languageId: [{ id: languageId, text: languageId }] }, { organization: organizationObj }); 
     }); 


    let getOrganization$ = this.userService.getOrganization(); 


    Observable.combineLatest(getOrganization$, updateUser$, (organizationList: any, user: any) => { 
     return { 
     organizationList: organizationList, 
     user: user 
     }; 
    }) 
     .subscribe((data: any) => { 
     // pre populate the form 
     let user = data.user; 
     if (user) { 
      Object.keys(user).forEach(key => { 
      const control = this.userForm.get(key); 
      if (control) { 
       control.setValue(user[key]); 
       control.markAsDirty(true); 
      } 
      }); 
     } 

     this.organizationList = data.organizationList.map(o => o.name); 

     }, err => this.error(err)); 


    Observable.combineLatest(getOrganization$, createUser$, (organizationList: any) => { 
     return { 
     organizationList: organizationList, 
     }; 
    }) 
     .subscribe((data: any) => { 
     this.organizationList = data.organizationList.map(o => o.name); 
     }, err => this.error(err)); 

我應該如何這個問題,rxjs

+0

我不明白爲什麼第二個combineLatest不工作​​,如果第一個dow,但我可以告訴this.userService.getOrganization將被調用兩次,因爲每個組合最新使用它。可觀察的是冷的 - 兩個訂閱。也不確定ow通常這個參數應該得到新的id,每個組合中的getOrganization $ - 如果這是http並且是完整的,將只發出一個值,所以這意味着每個組合將發出最大一個值。 –

+0

雅,第二次結合最新也被稱爲。 params(id)在ngOnInit上被調用,我使用相同的組件來創建用戶和更新用戶,是否有更簡單的方法來獲得相同的解決方案。 所以只有一個組合最新將被調用,所以只有一個getOrganziation $每頁加載 – vito

回答

1

類似的東西模型將做的工作。用http和路由器替換虛擬observables。這只是一個模擬器。

let routes$ = Rx.Observable.create((observer) => { 
    observer.next({id:1}); 
    setTimeout(()=> observer.next({xx:1}), 1000); 
    setTimeout(()=> observer.next({id:2}), 2000); 
    setTimeout(()=> observer.next({xx:2}), 3000); 
    setTimeout(()=> observer.next({id:3}), 4000); 
}); 

let [updateUser$, createUser$] = 
    routes$ 
    .map(params=> params['id']) 
    .partition(id => !!id); 


updateUser$ 
    .switchMap(id=>Rx.Observable.of(`${id}_user`)) 
    .switchMap(user=>Rx.Observable.of('organizationList'), 
     (user, organizationList) => ({user, organizationList}) 
).subscribe(x=>console.log(x)); 

createUser$ 
    .switchMap(id=>Rx.Observable.of('organizationList')) 
    .map(organizationList=> ({organizationList})) 
    .subscribe(x=>console.log(x)); 
+0

感謝使用flatmap而不是combine – vito