首页 > 解决方案 > http拦截器的错误处理在Angular中不起作用

问题描述

我正在研究 Angular 8

我正在尝试通过拦截器集中错误处理

我的拦截器代码正在运行,但它没有返回任何错误

import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpResponse,
    HttpErrorResponse
   } from '@angular/common/http';
   import { Observable, throwError } from 'rxjs';
   import { retry, catchError } from 'rxjs/operators';
import { RestService } from './restservice';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';


@Injectable()
   export class HttpErrorInterceptor implements HttpInterceptor {

    constructor(private rest : RestService , private route : Router){}



    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      // console.log('jcsjdsjd');
      // console.error('xjxfjb');
      // console.log(request);
      // console.log(next);
      return next.handle(request).pipe(catchError(err => {
        console.log(err);
          if (err.status === 401) {
              // auto logout if 401 response returned from api
              // this.authenticationService.logout();
              location.reload(true);
          }

          const error = err.error.message || err.statusText;
          return throwError(error);
      }))
  }
} 

我还在 app.module.ts 的 Providers 中定义了拦截器

  providers: [RestService  , AuthGuard ,   commonRest    ,  {
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true
  }],

我收到的错误 403 请求的响应是:

    {
  "messagecode": 403,
  "message": "not valid token!"
}

标签: angularangular8angular-httpclientangular-http-interceptors

解决方案


为了在全局范围内使用拦截器,并且提供程序位于核心模块中,应在拦截器顶部添加 @Injectable({ providedIn: 'root' }) ,如此处https://stackblitz.com/edit/angular-http-interceptor-working-for -lazy-loaded-module?file=src/app/core/token-interceptor.service.ts


推荐阅读