簡體   English   中英

可以取消HttpClient GET請求嗎?

[英]Possible to cancel HttpClient GET request?

我運行一個內部Angular項目,想向其中引入“取消請求”按鈕。 我們有一個帶有一堆參數的搜索功能,但是這些請求最多可能需要兩位數的秒數(10及以上)。 通常,當有人在搜索字段中鍵入過於明確的內容時就會發生這種情況,因為我們進行的是“包含”搜索。

我希望能夠取消這些請求,因此返回到組件時我的代碼無法執行。 這樣,我可以快速取消請求並發送新請求。

現在,我將按鈕設置為“禁用”,因此用戶無法輕松發送新請求。 如果我不這樣做,則會發生以下問題:

  1. 發送請求_1
  2. 發送請求_2
  3. request_2在3秒內完成,並在頁面上顯示結果
  4. request_1在10秒內完成並替換頁面上的結果

顯然,這不是最佳選擇。

要使用的代碼(單擊Get stuff按鈕,然后出現取消按鈕): https : //stackblitz.com/edit/angular-cgmyvc

為了能夠取消請求,您首先應該停止將observable轉換為Promise,而是使用訂閱。

您的服務應為:

export class TestService {
  constructor(private http: HttpClient) { }

  public GetStuff() {
    return this
      .http
      .get("https://jsonplaceholder.typicode.com/todos/1")
  }
}

現在,它返回一個可觀察的而不是應許的。

然后在您的組件中:

export class AppComponent  {
  constructor(private service: TestService){}
  public request;
  public Result;
  public GettingStuff = false;

  async ngOnInit() {

  }

  public GetStuff() {
    this.GettingStuff = true;
    this.request = this.service.GetStuff().subscribe((res) => {
      this.Result = JSON.stringify(res);
      this.GettingStuff = false;
    })
  }

  public async CancelGettingStuff() {
    console.log('cancelled');
    this.request.unsubscribe();
    this.GettingStuff = false;
  }
}

如您現在所見,我將訂閱放入變量request 如果有必要取消請求-我們只需調用一個unsubscribe方法。 這是工作中的閃電戰 我建議在測試之前通過開發人員工具模擬緩慢的Internet。

每次按cancel按鈕,您都會看到該請求被取消。

您必須像這樣導入它:

import { Subscription } from 'rxjs/Subscription';

編輯角度6

import { Subscription } from 'rxjs';



import { Component } from '@angular/core';
import { TestService } from './services/test-service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(private service: TestService){}
  public Result;
  public GettingStuff = false;
    res: Subscription;
  async ngOnInit() {

  }

  public async GetStuff() {
    this.GettingStuff = true;

     this.res = await this.service.GetStuff(); 
    console.log(this.res);
    this.Result = JSON.stringify(this.res);

    this.GettingStuff = false;
  }

  public async CancelGettingStuff() {
    this.res.unsubscribe();
    this.GettingStuff = false;
  }
}

希望這對你有用。

您可以使用switchMap運算符,該運算符將自動取消訂閱先前的可觀察對象。

你可以參考這個stackblitz

不確定是否可以通過promises來實現(可能不應該這樣做),但是使用RxJS和Angular的HttpClient就像取消訂閱一樣簡單:

// to send
const requestSubscription = this.httpClient.get(/* ...args */);

// to cancel
requestSubscription.unsubscribe();

暫無
暫無

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

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