使用Angular10。我的error.interceptor.ts文件不会被调用。
注意“ this.http.post(url,body,httpOptions);”这个不叫?
我不确定为什么吗?
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AlertService } from '../../dashboard/alert/alert.service';
import { AuthService } from '../auth/auth.service';
import { Router } from '@angular/router';
import { GlobalService } from '../api/global.service';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(
private alertService: AlertService,
private http: HttpClient
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(err => {
let error = 'Ut oh, there was an error mate...';
if (err.error != null) {
if (err.statusText) {
error = err.statusText;
}
if (err.message) {
error += ': ' + err.message;
}
}
if (err.status === 401) {
// console.log("error 401");
// auto logout if 401 response returned from api
// this.authenticationService.logout();
// location.reload(true);
}
//
const url = 'log/logEvent';
const body = 'test';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
this.http.post<any>(url, body, httpOptions);
// Send error to the view for alert
this.alertService.error(error);
return throwError(error);
}));
}
}
答案 0 :(得分:1)
您是否在App.module中注册了它? :) 应该看起来像这样:
providers: [{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }]
编辑:
我认为这只是缺少的订阅。您的通话应如下所示:
this.http.post(url, body, httpOptions).subscribe((res) => null)
答案 1 :(得分:0)
拦截器处理所有请求,处理或读取请求中的数据。
如果您正在使用定制模块,则应将其导入cusotme.module.ts文件中,否则将其导入app.module.ts中以使拦截器正常工作
providers: [
MyService,
MyOtherService,
...,
AuthGuard, // <- implements canActivate
RoleGuard, // <- implements canActivate
...,
// Interceptor
{
provide : HTTP_INTERCEPTORS,
useClass : TokenInterceptor, // Your intercepter
multi : true
}
],
// continue...
],