📜  角度取消 http 请求 - TypeScript 代码示例

📅  最后修改于: 2022-03-11 14:48:12.491000             🧑  作者: Mango

代码示例1
// http-cancel.service.ts
// use this service as DI in component
import {Subject} from 'rxjs';
import {Injectable} from '@angular/core';

@Injectable()
export class HttpCancelService{
  private cancelPendingRequestSubject=new Subject()
  cancelPendingRequest$ = this.cancelPendingRequestSubject.asObservable();

  cancelPendingRequest(){
    this.cancelPendingRequestSubject.next();
  }
}

==============================================================
//http-cancel-interceptor.service.ts
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, takeUntil} from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpCancelService} from './http-cancel.service';
import {tap} from 'rxjs/operators';

@Injectable()
export class CancelInterceptor implements HttpInterceptor{
  constructor(private cancelService: HttpCancelService) {
  }

  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    return next.handle(req).pipe(takeUntil(this.cancelService.cancelPendingRequest$
      .pipe(tap(()=> {throw new Error('Request is canceled')}))));
  }
}
==============================================================
 // app.module.ts
  import {HTTP_INTERCEPTORS} from '@angular/common/http';
  ...
  providers: [
    ...
    {provide: HTTP_INTERCEPTORS, useClass: CancelInterceptor, multi: true}
    ...
  ],