我正在使用 Angular 6 应用程序。在我的例子中,我有一种情况,我必须调用另一个 API 并获取数据,然后传递给第一个 API,然后恢复 API。
例如,在.ts
文件中:
logout(){
this.apiService.POST({}, "logout").subscribe((response: any) =>
{
alert("Logout subscribed returns...");
}
}
在api.service.ts文件中:
POST(param, apiName) {
var URL = Config.POST_ENDPOINT_URL + apiName; // Make whole API string
return this.http.post(URL, param, options)
.map(data => {
// Hear I have to call another HTTP API call
// if I got specific status code in data.
var apiRes: any = data;
if(apiRes.code == 500){
// Hear I need to call another API call
this.another()subscribe((anotherResponse) => {
console.log("anotherResponse :::" , anotherResponse);
// Now the main issue is come in picture. I need data form
// anotherRespose and pass in POST to continue API call.
// In short , I need to again call POST function with new data.
})
}
});
}
another(): Observable<any> {
return this.http.post(URL, obj, options)
.map(data => {
alert("another data return...");
return data; // Need to pass this data
})
}
此外,当我调用 logout()
时,它会在 another()
运行时返回它已订阅。因此,我需要同步设置流程。
最佳答案
试试这个
POST(param, apiName) {
return new Observable<number>(observer => {
var URL = Config.POST_ENDPOINT_URL + apiName; // Make whole API string
this.http.post(URL, param, options)
.subscribe(data => {
// Hear I have to call another HTTP API call
// if I got specific status code in data.
var apiRes: any = data;
if(apiRes.code == 500){
// Hear I need to call another API call
this.another()subscribe((anotherResponse) => {
console.log("anotherResponse :::" , anotherResponse);
observer.next(anotherResponse);
observer.complete();
})
}
});
}
}
关于angular - 如何在 Angular 6 同步运行的第一个订阅中使用第二个订阅返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52659674/