Angular HttpClient使用令牌

时间:2019-01-28 12:33:21

标签: angular api jenkins angular-httpclient

我正在尝试使用HTTPClient从Jenkins JSON-API中获取数据。由于我要访问的数据受到限制,因此需要针对Jenkins进行身份验证。因此,我生成了一个API令牌。现在,我想使用Angular HTTPClient进行身份验证,但是我不知道如何。

有人可以帮助我解决我的问题吗?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用HttpInterceptor在每个传出的http请求上附加其他标头。

@Injectable({
  providedIn: 'root'
})
export class OutgoingInterceptor implements HttpInterceptor {



  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

     interceptedRequest = req.clone({
         setHeaders: {

             // These headers is for Passport authentication.
             // You might to change these headers as you need
             // Also you need to store your token in localStorage etc.

             Accept: 'application/json',
             Authorization: tokenData
         }
     });

     return next.handle(interceptedRequest);
  }
}

您需要将此新创建的拦截器添加到模块的提供程序数组中:

providers: [

    ... 

    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    }
]
相关问题