2017-01-24 5 views
0

私は別の残りのリソースに照会し、その結果を単一のオブジェクトに結合したいと考えています。そのユーザーオブジェクトとすべてのユーザーには、1つの役割が含まれている必要があります。私はこれを行うにはflatMapを使用することができます読んだことがあるが、私はそれを動作させるカント:擬似コードのflatMapを使用してオブジェクトをネストする方法は?

public getUsers(): Observable<User[]> { 
    var users: Observable<User[]> = this.someService.getUsers('[A_URL]') // returns Observable<User[]> 
    .flatMap(res=> { 
     // for every user call resource 'role' and add it to user object one by one ... 
     // return this.someService.getRoleByUser('[A_URL_WITH_USERID]') 
    }.map(res=>{ 
     //add role to user object 
     // user.role = r; 
    }); 
); 
    return users; 
} 

イム申し訳ありませんが、私は実際の構文を理解しません。問題は、2番目のリソースコールでは、最初のコールからのすべてのユーザーのIDが必要であるということです。ここで

答えて

2

は、あなたがそれを行うことができます方法は次のとおりです。

// This obs emits a SINGLE array of all users. 
// Analog to what your `.getUsers()` method would return 
const usersArray = Rx.Observable.of([ 
    { id: 1, name: 'user1' }, 
    { id: 2, name: 'user2' }, 
    { id: 3, name: 'user3' } 
]); 

// Obtain the role(s) for a given user. 
const userRoles = function(userId) { 
    return Rx.Observable.of(`Role for user ${userId}`); 
} 

const obs = usersArray 
       // Flatten the array. 
       // Now each user is emitted as an individual value. 
       .mergeMap(val => val) 
       // Fetch user roles 
       .mergeMap(user => { 
       return userRoles(user.id).map(role => { 
        // Put together user + role 
        user.role = role; 
        // DO NOT FORGET to return below 
        return user; 
       }); 
       }) 

       // At this point, you have individual users with a `user.role` property 
       // being emitted in the stream. 

       // Unflatten the array if desired (to obtain a SINGLE array of ALL users) 
       .reduce((acc, curr) => acc.concat(curr), []); 

// Final subscribe 
obs.subscribe(val => console.log(val)); 

JS BINは、このコードをデモ:http://jsbin.com/vucuga/4/edit?js,console

注:

  • flatMap()mergeMap()の別名です。 RxJS 5(Angularが使用する)では、mergeMap()が「公式」演算子であると私は信じている。
  • ユーザーの順序を保持する必要がある場合は、mergeMap()の代わりにconcatMap()を使用してください。
+0

私は 'flatMap'がRxJS 5に存在しないと信じています:) https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35 – smnbbrv

+0

確かに。それが私が「メモ」に書いたものです。 :) – AngularChef

+0

ありがとうございました。今は、役割はユーザーの財産ではないと私に伝えています。どのようにタイプを保持できますか? – Stefan

関連する問題