# 拦截器
# 1. 创建 HttpInterceptor
import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
import {environment} from "../../../environments/environment";
@Injectable()
export class HttpResponseInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
if (event.body && event.body.errorCode && event.body.errorCode === '-403') {
window.location.href = environment.loginUrl;
}
}
return event;
})).pipe(catchError((error: HttpErrorResponse) => this.handleErrorResponse(error)));
}
private handleErrorResponse(event: HttpResponse<any> | HttpErrorResponse): Observable<any> {
// 前端异常统一处理
return throwError(event);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 2. 注册拦截器
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {HTTP_INTERCEPTORS, HttpClientModule} from "@angular/common/http";
import {HttpResponseInterceptor} from "./util/http-response.interceptor";
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpClientModule
],
declarations: [
],
exports: [
FormsModule,
],
providers:[
{provide: HTTP_INTERCEPTORS, useClass: HttpResponseInterceptor, multi: true}
]
})
export class ComModule {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
← 常用指令 mathjax公式渲染 →