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.

6
  • What is it doing right now? Commented Aug 15, 2017 at 16:22
  • It's sending an object. which is of no use?I am retrieving this value like this.jwtToken=this.authService.getUsableToken(); Commented Aug 15, 2017 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. Commented Aug 15, 2017 at 16:31
  • Possible duplicate of Angular2 - Use value of Observable returning method in another Observable Commented Aug 15, 2017 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. Commented Aug 15, 2017 at 18:43

1 Answer 1

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))
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Glad to hear :) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.