Flattening nested Observables

前端 未结 2 1592
梦毁少年i
梦毁少年i 2020-12-19 01:42

I\'m a stuck in nested observable hell and could do with a hand.

I have the following block of code

return this.findUser(term).map( users => {
  r         


        
2条回答
  •  再見小時候
    2020-12-19 02:47

    One solution would be to use forkJoin to join and then map the results of calls to getLastLogin to users:

    // forkJoin will return Observable, so use switchMap.
    
    return this.findUser(term).switchMap(users => Observable.forkJoin(
    
      // Map the array of users to the array of observables to be joined. Use
      // first to ensure the observables complete.
    
      users.map(user => this.getLastLogin(user.user_id).first()),
    
      // Use forkJoin's selector to add the last_login to each user and return
      // the users.
    
      (...logins) => {
        users.forEach((user, index) => { user.last_login = logins[index]; });
        return users;
      }
    ));
    

提交回复
热议问题