angular - Angular 拦截器不会调用 (POST)
问题描述
使用 Angular 10。我的 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);
}));
}
}
解决方案
你在 App.module 中注册了吗?:) 应该是这样的:
providers: [{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }]
编辑:
我认为这只是缺少订阅。您的电话应如下所示:
this.http.post(url, body, httpOptions).subscribe((res) => null)
推荐阅读
- c++ - 用 C++ 中的对象填充/初始化向量
- audio - 如何在一个命令中使用 FFMPEG 修剪静音和连接两个音频文件?
- node.js - GraphQL 自定义指令,无需在模式中显式声明
- c# - 用于条件替换的正则表达式以在日期中添加前导零
- java - 使用充气城堡解析 ASN 文件
- c# - Request.QueryString 没有返回正确的值
- r - 如果整个组满足条件,如何仅保留 data.frame 的那些行
- r - 基于分类处理的一般线性混合模型的图形预测结果如何
- python - 使用 python 多行解析 XML
- android - 如何在其中制作一个带有 ratngBar 的 RecyclerView,以便用户可以对 RecylerView 项目进行评分