簡體   English   中英

使用rxjs 6在angular 6中有新請求時如何取消正在進行的HTTP請求

[英]How to cancel ongoing HTTP requests when there's a new requests in angular 6 with rxjs 6

我的應用程序下面有兩個RxnsSearchServiceRxnsSearchHitCountService ,兩個HTTP服務。

使用forkJoin處理兩個請求,如下面的代碼所示。

 constructor( private rxnsSearchService: RxnsSearchService, private rxnsSearchHitCountService: RxnsSearchHitCountService ) { } const rxnsObservable: Observable<Array<any>> = this.rxnsSearchService.getReactions(this.searchParams, filters); const headCountObservable: Observable<number> = this.rxnsSearchHitCountService.getHitCount(this.searchParams, filters); forkJoin([rxnsObservable, headCountObservable]).pipe().subscribe((results) => { //handling results }, error => { console.log(error); }); 

每當有新請求出現時,我都想取消正在進行的舊請求。 誰能幫助我,使它變通?

 export class RxnsSearchService { sub: Subject<any> = new Subject(); constructor(private httpClient: HttpClient) {} getReactions(params: Params, offset: number, perPage: number, filters: any) { const body = { filters: filters, query: params.query }; return this.httpClient.post(environment.rxnsSearch, body).pipe( map((response: Array<any>) => { return response; }), catchError(error => { console.log(error); return throwError(error); }) ); } } 

 export class RxnsSearchHitCountService { constructor(private httpClient: HttpClient) {} getHitCount(params: Params, filters: any) { const body = { filters: filters, query: params.query, }; return this.httpClient.post(environment.rxnsSearchHitCount, body).pipe( map((response: number) => { return response; }), catchError(error => { console.log(error); return throwError(error); }) ); } } 

我將通過一個簡化的示例介紹如何做到這一點的一般方法。 說我們目前有這個:

public getReactions() {
  this.http.get(…)
    .subscribe(reactions => this.reactions = reactions);
}

確保取消舊請求的方法是改為發出某些主題:

private reactionsTrigger$ = new Subject<void>();

public getReactions() {
  this.reactionsTrigger$.next();
}

現在,我們有了一個可觀察到的代表觸發新請求的事件流。 現在,您可以將OnInit實施為以下形式:

public ngOnInit() {
  this.reactionsTrigger$.pipe(
    // Use this line if you want to load reactions once initially
    // Otherwise, just remove it
    startWith(undefined),

    // We switchMap the trigger stream to the request
    // Due to how switchMap works, if a previous request is still
    // running, it will be cancelled.
    switchMap(() => this.http.get(…)),

    // We have to remember to ensure that we'll unsubscribe from
    // this when the component is destroyed
    takeUntil(this.destroy$),
  ).subscribe(reactions => this.reactions = reactions);
}

// Just in case you're unfamiliar with it, this is how you create
// an observable for when the component is destroyed. This helps
// us to unsubscribe properly in the code above
private destroy$ = new Subject<void>();
public ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

    switchMap(() => this.http.get(…)),

在您的情況下,實際上可能會將事件切換到forkJoin

    switchMap(() => forkJoin([rxnsObservable, headCountObservable])),

如果您希望單個事件流重新觸發兩個請求。

看到一個顯示HTTP請求實際觸發的代碼段將很有幫助,但是很可能是一個UI組件,它在單擊時調用一個函數。

使用RxJS 6解決此問題的方法是使用一個Subject來接收click事件,然后使用switchMap運算符取消未完成的請求以防止背壓。 這是一個例子:

private clickSubject$: Subject<void> = new Subject();

constructor() {
    this.clickSubject$
        .pipe(switchMap(() => forkJoin([rxnsObservable, headCountObservable])))
        .subscribe((results) => // handling)
}

onClick() {
    this.clickSubject$.next(undefined);
}

如果您有多個要執行http請求的地方,則使用以下方法進入主題: this.clickSubject$.next(undefined) ;

您可以在RxJs中簡單地使用debounce運算符:

debounce(1000);

它提供了一種在發送任何請求之前設置延遲(以毫秒為單位)的方法,

該示例僅用一個請求替換了1000ms內觸發的所有請求。

有關更多詳細信息:

fromEvent(input, 'input').pipe(
       map((e: any) => e.target.value),
       debounceTime(500),
       distinctUntilChanged()
     ).subscribe(
       (data) => {
           this.onFilterTable({column: fieldName, data});
       }
     );

暫無
暫無

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

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