如何在角度6中同步使用第一个正在运行的订阅中的第二个订阅返回值

时间:2018-10-05 06:39:05

标签: angular api http observable

我正在使用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()运行时的订阅状态。因此,我需要将流设置为同步。先谢谢了。

2 个答案:

答案 0 :(得分:1)

尝试一下

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();
                })
            }

   });

 }

}

答案 1 :(得分:0)

您可以通过rxjs使用switchMap运算符。 您可以这样做:

this.http.post(url, param, options).pipe(
  switchMap(data => {
    this.another(); //where data is the response from your http post request
  })
);