使用rxjs 6在angular 6中有新请求时如何取消正在进行的HTTP请求

时间:2018-07-31 18:53:55

标签: javascript angular typescript rxjs

我的应用程序中有两个低于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);
      })
    );
  }
}

3 个答案:

答案 0 :(得分:2)

我将通过一个简化的示例介绍通用的方法。说我们目前有这个:

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])),

如果您希望单个事件流重新触发两个请求。

答案 1 :(得分:2)

看到一个显示HTTP请求实际 trigger 的代码段将很有帮助,但它很可能是一个UI组件,它可以在单击时调用一个函数。

使用RxJS 6解决此问题的方法是使用Subject接收点击事件,然后使用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);

答案 2 :(得分:1)

您只需在RxJs中使用反跳运算符即可:

debounce(1000);

提供了一种在发送任何请求之前设置延迟(以毫秒为单位)的方法,

该示例仅用一个请求替换了1000ms内触发的所有请求。

更多详细信息:

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