在HttpInterceptor内部拦截“预检” OPTION请求

时间:2019-07-23 14:10:30

标签: javascript angular typescript angular7 angular-http-interceptors

我正在尝试拦截http响应以管理Web应用程序中的重叠式微调器,我不得不放弃CORS生成的预检OPTION请求,但无法拦截它们。

我实现了以下代码:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse, HttpResponse, HttpEventType } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { ModalData } from '../../modal-dialog/modal-dialog.component';
import { ModalDialogService } from '../../modal-dialog/modal-dialog.service';
import { unescapeIdentifier } from '@angular/compiler';
import { SpinnerOverlayService } from './spinner-overlay.service';

@Injectable()
export class HttpInterceptorTimeoutService implements HttpInterceptor {
  timeoutInterval: number = 5000;
  timeout: NodeJS.Timer;

  constructor(
    private spinnerOverlayService: SpinnerOverlayService,
    private modalDialogService: ModalDialogService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.timeout = setTimeout(() => {  
      let dataModal: ModalData = {
        statusLabel: 'The HTTP call is taking longer than expected ... wait!',
        type: 'WARNING'
      };

      this.modalDialogService.openDialog(dataModal);  //open dialog
      this.spinnerOverlayService.hide();   // hide overlay 
    }, this.timeoutInterval);
    this.spinnerOverlayService.show();    //show overlay

    return next.handle(req).pipe(             //manage HTTP response
      map((event: HttpResponse<any>) => {
        if (event.status == null) { //ignore OPTION
          console.log("event.status == null",event);
          return event;
        } else {                // manage HTTP response
          console.log("event.status != null",event);

          this.spinnerOverlayService.hide();    // hide overlay 
          this.modalDialogService.closeDialog();  //close dialog
          clearTimeout(this.timeout);     //stop scheduled execution
          return event;
        }
      })
    );
  }
}

map((event: HttpResponse<any>) => {...})中有一种方法可以区分OPTION响应和实际响应

0 个答案:

没有答案