Varun Gupta Varun Gupta - 1 month ago 14
HTTP Question

How to return the result received from http request inside http request in ionic 2 framework using angular 2.My code is following

getUsableToken() {

let platformName = "abc";
let platformId = "123123";

return this.http.get('http://localhost:17001/platform/' + platformId + '/key?name=' + platformName).map(res => res.json())
.subscribe(data => {

let secretKey = data.payload.platformInfo.key;

return this.http.get('http://localhost:17001/platform/' + platformId + '/token?name=' + platformName + '&key=' + secretKey).map(res => res.json())
.subscribe(data => {
return data.payload.token;

}, err => {
console.log(err);
});
},
err => {
console.log(err);
});
}


In this code I want to return
data.payload.token
. How to do that? Any help would be appreciated.

Answer Source

What you could do is to make use of flatMap (mergeMap) here, since the second call is dependent on the result of the first call, so something like this:

import 'rxjs/add/operator/mergeMap';

//....

getUsableToken() {
  return this.http.get('url')
    .map(data => {
      let secretKey = data.json().payload.platformInfo.key
      return secretKey;
    })
    // where 'key' is the parameter you need for the second call
    .flatMap(key => this.http.get('url').map(data => {
        let token = data.json().payload.token;
        return token;
    }))

}

and now where you subscribe you get the token:

doSomething() {
  this.myService.getUsableToken() 
    .subscribe(token => console.log(token))
}