我正在尝试拦截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响应和实际响应