簡體   English   中英

取消HTTP請求

[英]Cancel a HTTP request

我想知道是否可以通過某種方式檢查HTTP Get是否處於掛起狀態以及是否可以取消HTTP Get?

這是我的HTTP獲取:

public getData(): Observable<any> {
   return this.httpClient.get('http://IP_ADRESS:3490/testStream', {responseType: 'arraybuffer', observe: 'response' }});
}

public putData(): void {
   this.getData().subscribe((resp) => {
     console.log(resp);
     const responseArray: Uint8ClampedArray = new Uint8ClampedArray(resp);
     const newTabTemp: Uint8ClampedArray = new Uint8ClampedArray(this.maxHeight * this.maxWidth * 4);
     let comp = 0;
     for (let i = 0; i < this.maxHeight * this.maxWidth * 4; i = i + 4) {
       newTabTemp[i] = responseArray[comp];
       newTabTemp[i + 1] = responseArray[comp];
       newTabTemp[i + 2] = responseArray[comp];
       newTabTemp[i + 3] = 255;
       comp = comp + 1;
     }
     let nouvData: ImageData;
     nouvData = new ImageData(newTabTemp, this.maxWidth, this.maxHeight);
     this.contextVideo.putImageData(nouvData, BORDERX / 2, BORDERY / 2);
   });
}

要求花很多時間 請求從不成功

我收到了很多這些未決請求,這些請求永遠不會成功或需要很長時間。 如何檢查它們是否正在等待中並取消它們?

在Angular 2+中,如果您在觀察到的請求上調用取消訂閱,則請求將中止。 subscription.unsubscribe()的自然行為是不會中止請求,但是angular 2家伙已經在angular / http包中添加了此特定功能。 請參閱 Angular github存儲庫。

在正常情況下(當不使用angular / http時),如果要在退訂時中止請求,則可以利用以下代碼-

Observable.create((observer) => {

        function cancelRequest() {
            // Clear any even listeners added previously.

            request.abort();
        }

        // Other request processing related code

        request.send(formData);

        return () => {
            cancelRequest();
        };
    });

取消訂閱可觀察項具有相同的取消作用。 在下面的示例中,http請求將在2秒內取消。 您可以在此處查看完整的示例

search() {
const request = this.searchService.search(this.searchField.value)
  .subscribe(
    result => { this.result = result.artists.items; },
    err => { this.errorMessage = err.message; },
    () => { console.log('Completed'); }
  );

setTimeout(() => request.unsubscribe(), 2000);

}

取消HTTP請求是常見的要求。 例如,您可能有一個請求隊列,其中新請求取代了待處理請求,而該待處理請求需要取消。 登錄以發表評論

要取消請求,我們調用其訂閱的取消訂閱功能

 @Component({ /* ... */ })
    export class AppComponent {
      /* ... */

      search() {
        const request = this.searchService.search(this.searchField.value)
          .subscribe(
            result => { this.result = result.artists.items; },
            err => { this.errorMessage = err.message; },
            () => { console.log('Completed'); }
          );

        request.unsubscribe();
      }
    }

禮貌: 取消http請求

暫無
暫無

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

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