Angular 9 - maszynopis - headers.set - bez dodawania nagłówka

Oct 02 2020

Próbuję użyć wtryskiwacza kątowego, aby dodać token okaziciela

mimo że kod jest wykonywany, nagłówek nie jest dodawany

istnieje wiele różnych kodów, wypróbowałem niektóre z nich, wszystkie prowadzą do tego samego problemu

Żaden okaziciel nie jest wysyłany z żądaniem

na poniższym obrazku zatrzymałem się na clone / headers.set , ale nawet po tym kroku mapa nagłówków jest nadal pusta

@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);
  }
}

dzięki za pomoc w tej sprawie

Odpowiedzi

1 Adjunta Oct 02 2020 at 10:01

Zgodnie z prototypem metody clone () otrzymałeś właściwość obiektu do ustawiania nagłówków (nazwaną setHeaders)

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

Należy wykonać następujące czynności

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