import { catchError, finalize, tap } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; /** * HTTP请求访问耗时拦截器 */ @Injectable() export class NaDefaultHttpTimingInterceptor implements HttpInterceptor { constructor() { } intercept(req: HttpRequest, next: HttpHandler): Observable> { // this.loadingService.start(); const started = Date.now(); return next.handle(req).pipe( tap(event => { if (event instanceof HttpResponse) { const elapsed = Date.now() - started; console.log(`%cRequest [${req.method}] for ` + req.urlWithParams + ' took ' + elapsed + ' ms.', 'background: #222; color: yellow'); } }), finalize(() => { // this.loadingService.stop(); }), catchError((error: any) => { const elapsed = Date.now() - started; console.log(`%cRequest [${req.method}] for ` + req.urlWithParams + ' took ' + elapsed + ' ms.', 'background: #222; color: red'); return throwError(error); }) ); } }