angular - 如何在 Angular 6 同步运行的第一个订阅中使用第二个订阅返回值?

标签 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() 运行时返回它已订阅。因此,我需要同步设置流程。

最佳答案

试试这个

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/

相关文章:

api - GET,然后操作该信息(while 循环和 if 语句),然后 PUT

ruby - 如何使用 ruby​​ 检查 Amazon S3 上的 URL 是否有效且未过期

angularjs - 未找到翻译 - Jhipster/Angular

html - 我想做图像中心

angular - 如何调试 Angular2/Typescript 中的 Observable 值?

java - Android HttpURLConnection 奇怪的响应

javascript - 连接 Ajax "GET"的下载

cordova - 使用 angular2 - ionic 2 下载文件

api - 根据 fliptop 或 fullcontact 等电子邮件获取推特 ID

api - 如何从 paypal 帐户获取客户端 ID 和 key