簡體   English   中英

如何從角度2的函數返回訂閱數據?

[英]How to return subscribed data from a function in angular 2?

我有一個函數,該函數有多個使用for循環的API調用。 我希望連接所有訂閱的響應,並在訂閱最后一個API調用的數據時返回它。

我能夠在函數內部獲取組合數據,但返回值從調用它的位置得到了不確定。 我正在調用此函數來映射響應。 這些都是我服務的一部分而不是任何組件。 我無法改變結構,所以即使不是正確的方法,有沒有可行的解決方案? 我是角度2的新手。

call()
{
    http.get(url)                                                            
        .map((res) => this.doll(res)) /*here the function returning undefined */
        .subscribe(/*something*/);
}
doll(res) : Observable /*type*/
{                                                                           
   for(looping through this APIs)                                                
   {                                                                               
   http.get(url)                                                              
       .map((res) => res)                                                   
       .subscribe((data: any) =>{                                         
           /*concatenate response */                                           
           if(certain condition)                                             
           {                                                               
               /*getting all the data together */                                
               console.log(data); /*working fine and getting the desired data*/    
               return data;                                                   
           }                                                        
       });                                                               
   }                                                                               
}

Tirtha,你必須使用forkJoin來獲得一個Unique observable。 然后你可以訂閱observable。 通常,您使用管理調用的服務和訂閱服務的組件

//your service
doll() : Observable<any[]> //return an array of anys
{      
   //I supouse you has in APIS some like
   APIS=[this.http.get("url1"),this.http.get("url2"),this.http.get("url3")...]
   return forkJoin(APIS);                                                                   
}


//So, In a component (if you inject hte service), you can subscribe to "doll"
this.myService.doll().subscribe(res=>{
    console.log(res[0]) //the response to http.get("url1")
    console.log(res[1]) //the response to http.get("url2")
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM