首页 > 解决方案 > 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);
    }));
  }
}

标签: angular

解决方案


你在 App.module 中注册了吗?:) 应该是这样的:

providers: [{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }]

编辑:

我认为这只是缺少订阅。您的电话应如下所示:

this.http.post(url, body, httpOptions).subscribe((res) => null)


推荐阅读