[英]How to use second subscription return value in first's running subscription in sync in angular 6?
I am using angular 6 app.我正在使用 angular 6 应用程序。 In my case I have a one situation, in which I have to call another API and take data and then pass to first API and then resume API.在我的情况下,我有一种情况,我必须调用另一个 API 并获取数据,然后传递给第一个 API,然后恢复 API。
For example, in .ts
file:例如,在.ts
文件中:
logout(){
this.apiService.POST({}, "logout").subscribe((response: any) =>
{
alert("Logout subscribed returns...");
}
}
In api.service.ts file:在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
})
}
In addition, when I call logout()
it will return it's subscribed while another()
is running.此外,当我调用logout()
它会在another()
运行时返回它已订阅。 So, I need to set my flow in a sync.所以,我需要同步设置我的流程。
Try this尝试这个
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();
})
}
});
}
}
You can use the switchMap operator by rxjs.您可以通过 rxjs 使用 switchMap 运算符。 You can do it like this:你可以这样做:
this.http.post(url, param, options).pipe(
switchMap(data => {
this.another(); //where data is the response from your http post request
})
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.