Angular9-typescript-headers.set-ヘッダーを追加しない

Oct 02 2020

角度インジェクターを使用してベアラートークンを追加しようとしています

がコードが実行され、ヘッダが付加されていません

そこには多くの異なるコードがあります、私はそれらのいくつかを試しました、それらはすべて同じ問題につながります

ベアラはリクエストとともに送信されません

以下の画像では、clone / headers.setで停止しましたが、そのステップの後でも、ヘッダーマップはまだ空です。

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(
    private appService: AppService
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add auth header with jwt if user is logged in and request is to the api url
    let authentication: Authentication = this.appService.getUserSession();

    const isLoggedIn = authentication && authentication.token;
    const isApiUrl = request.url.startsWith(environment.apiUrl);

    //------------------------------------- add id's
    let body = request.body;
    if(!body)
    {
        body={};
    }
    body['clientId'] = environment.clientId;
    body['clientSecret'] = environment.clientSecret;

    request = request.clone({
        body: body
    });

    //--------------------------------------- add jwt

    if(authentication)
    {
        request = request.clone(
            {
                headers: request.headers.set('Bearer', authentication.token)
            }
        );
    }

    return next.handle(request);
  }
}

これで私を助けてくれてありがとう

回答

1 Adjunta Oct 02 2020 at 10:01

clone()メソッドのプロトタイプによると、ヘッダーを設定するためのオブジェクトプロパティ(setHeadersという名前)を取得しました

setHeaders?: {
            [name: string]: string | string[];
        };

あなたは次のようにすべきです

 request = request.clone(
         {
            setHeaders: {
                Authorization: `Bearer ${authentication.token}`
            }
         }
    );