代码之家  ›  专栏  ›  技术社区  ›  Sachin Shah

如何在angular 6中的first运行同步订阅中使用second subscription返回值。

  •  1
  • Sachin Shah  · 技术社区  · 8 年前

    我正在使用angular 6应用程序。在我的例子中,只有一种情况,我必须调用另一个API并获取数据,然后传递到第一个API,然后恢复API。

    例如,在 .ts 文件:

    logout(){
      this.apiService.POST({}, "logout").subscribe((response: any) => 
      {
          alert("Logout subscribed returns...");
      }
    }
    

    api.服务.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 回复  |  直到 6 年前
        1
  •  1
  •   Kruti Choksi Patel    8 年前

    试试这个

    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();
                    })
                }
    
       });
    
     }
    
    }
    
        2
  •  0
  •   Bon Macalindong    8 年前

    你可以这样做:

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