2017-07-14 171 views
2

我正在用Angular2構建一個網站,其中包含多個包含具有各種統計信息的儀表板的頁面。Angular 2 - 在路由更改中取消HTTP請求

在單個頁面上,分別製作了6個不同的請求(每個儀表板圖塊一個),這可能需要5秒鐘才能結束。當儀表板的請求正在進行時,當我更改頁面時,會出現問題。

在這種情況下,請求將開始疊加,如果多次更改頁面,儀表板將花費更多時間加載。每個請求都作出如下方式:

return this.http.post("http://mywebsite.com/dashboard/info", body, options) 
    .map((res) => { 
     return res.json() 
    }).subscribe((result) => { /* do something */}); 

我所尋找的是一種方式來中止所有當我改變網頁的當前請求,以避免它們疊加起來,導致過多的加載時間。

+1

https://stackoverflow.com/questions/36490926/how-to-cancel-a-httprequest-in-angular-2 – onetwo12

+1

在'ngOnDestroy'生命週期掛鉤'從你的HTTP調用unsubscribe'。 – echonax

回答

3

當您致電subscribe時,Subscription對象被創建並且它一直存在,直到observable完成。

如果您不再需要結果,您必須從發佈請求中獲得unsubscribe。最常見的方法是從ngOnDestroy組件中調用unsubscribe

/** 
* Disposes the resources held by the subscription. May, for instance, cancel 
* an ongoing Observable execution or cancel any other type of work that 
* started when the Subscription was created. 
* @return {void} 
*/ 
unsubscribe(): void; 

編輯:

注意,就是你所謂share()take()first()或創建一個比退訂不會取消HTTP請求一個新的觀察到的任何其他操作。因爲您只會取消訂閱兒童可見度。

+0

只是爲了確認,調用上述任何方法都會創建一個新的observable,其中取消訂閱不會取消HTTP請求,這是否正確? –

+0

@ManuelReis對你有幫助嗎?因爲我理解你的問題的方式,你似乎實際上並沒有破壞組件(ngOnDestroy不會被調用)。 – AArias

+0

@AArias我也認爲(和ngOnDestroy沒有被導入我的組件),但顯然在更改頁面ngOnDestroy被調用。我現在正在驗證這種方法是否有效 –

2

您想要取消訂閱您的可觀察訂閱。訂閱在訂閱observable(本例中爲this.http.post())時返回。然後,在頁面的OnDestroy方法中,您可以取消訂閱,取消正在進行的http請求。

// subscription 
this.subscription = this.http.post("http://mywebsite.com/dashboard/info", body, options) 
    .map((res) => { 
     return res.json() 
    }).subscribe((result) => { /* do something */}); 

// within the ngOnDestroy of your component 
onDestroy(){ 
    this.subscription.unsubscribe(); 
}