2017-10-18 75 views
0

我無法弄清楚如何使用Http請求的結果來發出另一個Http請求。讓我們用例子來說清楚; 從這個API首先,我得到的數據:Angular 4 Http Chain Requests

[{"id": 1}] 

從另一個API和結果第二,我應該得到的數據是:

[{"id": 1, "name": "id labore ex et quam laborum", }] 

所以我應該檢查的API,如果第一個數據id =1那麼我應該張貼"id labore ex et quam laborum"。我打開任何建議。謝謝

+0

你的問題還不清楚......據我所知,你想申請第二個姓名:id labore ex et quam labourum「如果第一個http請求,響應是> id:1,對吧? – Amit

+0

是的,這就是如果第一個API結果是1,那麼我應該發佈html「id labore ex et quam labourum」 – Ryoush

+0

試試這個.http.get(url).subscribe((data)=> if(data.id == 1)this。 http.post(網址,數據)) – Amit

回答

1

您可以使用rxjs switchMap運算符。

只需導入:

import 'rxjs/add/operator/switchMap'; 

,然後用它是這樣的:

this.http.get('/api/items').switchMap(data => { 
    // do something with your data 
    return this.http.get(`https://api.com/${data.id}`); // use it for example in your http request 
}).subscribe(data => { 
    this.results = data['results']; 
}); 

你可以找到更多關於它here