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);
});
}
在此代码中,我想返回data.payload.token
。怎么做?任何帮助将不胜感激。
答案 0 :(得分:1)
你可以做的是在这里使用flatMap
(mergeMap
),因为第二次调用取决于第一次调用的结果,所以像这样:
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;
}))
}
现在您订阅的地方获得了令牌:
doSomething() {
this.myService.getUsableToken()
.subscribe(token => console.log(token))
}