簡體   English   中英

Angular, RxJS - 如何使用 switchMap 取消以前的請求?

[英]Angular, RxJS - How to cancel previous requests using switchMap?

我試圖自己弄清楚很長一段時間,但我堅持了下來。

我的情況:我有一個數據表,當用戶進入頁面時,請求轉到 REST API。 表格上方有一個表格,用於指定/過濾表格的結果。 當用戶單擊按鈕時,帶有查詢參數的新請求將發送到服務。

我正在嘗試找到一種方法來在用戶單擊按鈕時停止先前的請求,以搜索具有特定參數的表

這是我到目前為止所做的stackblitz 也許我的方法是錯誤的,有人可以告訴我如何更好地編寫它,或者也許只有幾件事需要糾正。

感謝您的任何幫助

您可以在pipe中使用takeUntil運算符,並將主題傳遞給它,並且每次應用新過濾器時,您都可以向該主題發出一些內容以取消訂閱之前的訂閱並再次訂閱:讓我舉個例子說明如何使用此運算符:

無論您的代碼是否有效! 我只添加了有關如何使用 takeUntil 運算符的部分!

...
 unsubscribe = new Subject<boolean>();

  constructor(private _service: ServiceConnectService) {}

  ngOnInit() {
    this.clickStream
      .pipe(
        map(() => console.log(1)),
        switchMap(() => {
          return this.getMethodServicesInstances();
        }),
        takeUntil(this.unsubscribe) // this will be executed once you call next with a value!! and the subscription will be stopped!
      )
      .subscribe(results => {
        console.log(2);
      });
  }

  applyFilter(){
    this.unsubscribe.next(true);
    /*
      you can then rerun the subscription and reset the unsubscribe subject state to null!
     */
  }
...

暫無
暫無

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

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