首页 > 解决方案 > HttpInterceptor 不适用于所有请求

问题描述

我正在使用新版本的 Angular,我面临着在所有请求的请求标头中未发送授权令牌的问题。自从我升级到新版本 8 后,我检查了所有内容,但问题仍然存在。当我发送一些请求时,即使我在控制台中打印它以检查它的存在,我也找不到授权标头。

这是 Angular 8 的新版本。

import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpEvent,
  HttpHandler,
  HttpRequest
} from '@angular/common/http';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(
    req: HttpRequest,
    next: HttpHandler
  ): Observable> {
    // Retrieve logged in user if connected
    const userToken = this.authService.getAuthenticatedUser();
    // Verify existing of the user
    if (userToken != null && userToken.bearerToken != null) {
      req = req.clone({
        setHeaders: {
          Authorization: userToken.bearerToken
        }
      });
    }
    return next.handle(req);
  }
}

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    FooterComponent,
    HomeComponent,
    ContactUsComponent,
    NotFoundComponent,
    CartComponent,
    LoginComponent
  ],
  imports: [BrowserModule, AppRoutingModule, CustomModule, LayoutModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

我期待有授权标头。

标签: javascriptangulartypescripthttp

解决方案


导入HTTP_INTERCEPTORS和您的服务并在提供程序中提供它们

<! app.module.ts -->
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { RequestInterceptor } from './your-interceptor-path'

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    }
  ]

您仅将Authorization标头克隆到HttpRequest

将以下行添加到标题克隆RequestInterceptor旁边的服务中Authorization

if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

req = req.clone({ headers: req.headers.set('Accept', 'application/json') });

推荐阅读