在module中provide
对请求做一些操作
对响应做一些操作
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { Router } from '@angular/router';@Injectable()
export class ResponseInterceptor implements HttpInterceptor {constructor(private router: Router) {}intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {return next.handle(request).pipe(tap((event: HttpEvent<any>) => {if (event instanceof HttpResponse) {// 在这里可以对响应进行处理console.log('Response Interceptor:', event);}}),catchError((error) => {// 捕获请求错误if (error.status === 500) {// 如果状态码是500,导航到登录页或者其他处理this.router.navigateByUrl('/login');}return throwError(error);}));}
}