1
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.

Mohd
  • 5,523
  • 7
  • 19
  • 30
  • What is it doing right now? – Jason Spradlin Aug 15 '17 at 16:22
  • It's sending an object. which is of no use?I am retrieving this value like this.jwtToken=this.authService.getUsableToken(); – Varun Gupta Aug 15 '17 at 16:24
  • Ah, these requests are asynchronous. You can't just "return" something immediately. `getUsableToken()` is returning a Subject (from `this.http.get(...).subscribe(...);` You could create a new Observable which contains the `data.payload.token` or a promise wrapping the same. – Jason Spradlin Aug 15 '17 at 16:31
  • Possible duplicate of [Angular2 - Use value of Observable returning method in another Observable](https://stackoverflow.com/questions/40613099/angular2-use-value-of-observable-returning-method-in-another-observable) – Ivar Reukers Aug 15 '17 at 18:39
  • That's true, But the problem here is that I have another get request in first http get request which is creating issue. – Varun Gupta Aug 15 '17 at 18:43
  • Solved using promise. – Varun Gupta Aug 16 '17 at 05:20

1 Answers1

1

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))
}
AT82
  • 71,416
  • 24
  • 140
  • 167