首页 文章

在发送请求后调用angular 6拦截器

提问于
浏览
1

我正在开发一个角度为6的app,我想在每个请求的authorize-header中添加一个jwt-token . 对于这种情况,我想使用拦截器 .

代码如下所示:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let sessionId = localStorage.getItem('sessionId');
    if (sessionId) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${sessionId}`
        }
      });

      console.log("With AuthHeader");
    }

    return next.handle(request);
  }
}

这是我发送请求的代码:

httpQuery(ressource): Observable<T[]> {
    var absoluteUrl = this.getAbsoluteUrl(ressource);
    console.log("Sending");
    return this.httpClient
      .get<T[]>(absoluteUrl);
  }

但是我面临以下问题:拦截器被触发,但是在发送请求之后 . 我可以在开发人员控制台中看到这一点,来自http方法的日志消息在来自拦截器的日志消息之前出现:
enter image description here

正如您所看到的,这会从服务器获得401响应,该响应需要授权标头 .

我阅读了大量有关拦截器的教程和stackoverflow问题,但我看不出自己的错误 .

也许有些人对我有暗示?

谢谢你,最诚挚的问候,Alex

2 回答

  • 0

    你所展示的就是好的

    console.log("Sending"); //here you print to the cosole
    return this.httpClient // here you actually MAKE http call.
      .get<T[]>(absoluteUrl);
    

    所以你的拦截器被称为DURING请求执行,并且在进行实际的XHR请求之前 .

  • 0

    请试试这个

    const headers = request.headers.append('Authorization', `Bearer ${sessionId}`);
    const d = request.clone({ headers: headers });
    
    return next.handle(request);
    

相关问题