微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 9 http Interceptor 获取 Aws accesstoken

如何解决Angular 9 http Interceptor 获取 Aws accesstoken

我正在按照此 this 在 Angular HTTP 拦截器中添加 AWS 访问令牌,但代码处于无限循环中,并且出现 net::ERR_INSUFFICIENT_RESOURCES 错误

token 值的 console.log 显示单个字符。

提前致谢

这是代码

service.ts

 getAccesstoken(): Observable<string> {
    return from(Auth.currentSession()).pipe(
      switchMap(session => from(session.getAccesstoken().getJwtToken()))
    );
  }

拦截器.ts

/* eslint-disable no-param-reassign */
import { Injectable } from '@angular/core';
import {
  HttpEvent,HttpInterceptor,HttpHandler,HttpRequest,} from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from 'app/user.service';

import { switchMap } from 'rxjs/operators';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public userService: UserService) {}

  intercept(
    req: HttpRequest<any>,next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return this.userService.getAccesstoken().pipe(
      switchMap(jwtToken => {
        console.log(jwtToken);
        // clone the request to add the new header.
        req = req.clone({
          headers: req.headers.set('Authorization',`Bearer ${jwtToken}`),});
        if (!req.headers.has('Content-Type')) {
          req = req.clone({
            headers: req.headers.set('Content-Type','application/json'),});
        }
        return next.handle(req);
      })
    );
  }
}

解决方法

在拦截器中使用 http 请求不是一个好习惯。相反,您可以在应用程序打开时拉取一次“jwtToken”并将其导入 localStarege。

在 app.module.ts

import {UserService} from './UserService';

export function appInitializerFn(userService: UserService) {
  return (): Promise<boolean> => userService.getJwtToken()
}

...

@NgModule({
 providers : [UserService,{
      provide: APP_INITIALIZER,useFactory: appInitializerFn,multi: true,deps: [UserService]
    },] )

在 UserService.ts 中

@Injectable()
export class UserService {
   

  constructor(private http: HttpClient) {
  }

  getJwtToken(): Promise<any> { 
    return this.http
      .get('get/toke/url'))
      .toPromise()
      .then((data: any) => {
        localStorage.setItem("jwtToken",data); 
      }).catch((err: Error) => {  
      }).finally(() => {
        console.info(' token init ');
        return Promise.resolve(true)
      })
  } 
}
intercept(
   req: HttpRequest<any>,next: HttpHandler
 ): Observable<HttpEvent<any>> {
   const jwtToken: string = localStorage.getItem('jwtToken');

   req = req.clone({
         headers: req.headers.set('Authorization',`Bearer ${jwtToken}`),});
       if (!req.headers.has('Content-Type')) {
         req = req.clone({
           headers: req.headers.set('Content-Type','application/json'),});
       }
       return next.handle(req);
   );

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。