angularrxjsreactive-programmingangular2-observablesrxjs-dom

RxJS: Transfer values in stream


I want to create an observable which
1. Gets token with getToken2 method
2. Use this token to get userdata with flatMap
3. Assign just received userData and token( which was received via flatMap) to localStorage
The problem is that I am unable to access the token in second map method.
So How can I transfer this token value in stream so I can access it.

  getCurrentUser2() {
       return this.getToken2()
         .flatMap((token) => this.http.get(this.URL + '/ROS/profile?token=' + token))
         .map((res) => res.json().data)
         .map((response) => {

             localStorage.setItem('currentUser', JSON.stringify({
               token:token, ,**want to access token value here**
               userProfile: response
             }));
             localStorage.setItem('orgId', response.structure.id);
             return this.toUser(response, '12');

         });
  }

Please give me idea to solve this issue.
Kind Regards


Solution

  • The flatmap or mergeMap has an optional parameter called resultSelector.

    A function to produce the value on the output Observable based on the values and the indices of the source (outer) emission and the inner Observable emission. The arguments passed to this function are:

    outerValue: the value that came from the source
    innerValue: the value that came from the projected Observable
    outerIndex: the "index" of the value that came from the source
    innerIndex: the "index" of the value from the projected Observable

    return this.getToken2()
             .flatMap((token) => this.http.get(this.URL + '/ROS/profile?token=' + token),(token,response,outerIndex,innerIndex) => [token,response.json().data]))
             .map((response) => {
             //response is an array with both outer output and inner output.
                 localStorage.setItem('currentUser', JSON.stringify({
                   token:response[0], 
                   userProfile: response[1]
                 }));
                 localStorage.setItem('orgId', response[1].structure.id);
                 return this.toUser(response[1], '12');
    
             });