Angular 9 - typescript - headers.set - senza aggiunta di intestazione

Oct 02 2020

Provo a usare un iniettore angolare per aggiungere un gettone portatore

sebbene il codice venga eseguito, l'intestazione non viene aggiunta

ci sono molti codici diversi là fuori, ho provato alcuni di loro, tutti portano allo stesso problema

nessun portatore viene inviato con la richiesta

nell'immagine sotto mi sono fermato a clone / headers.set , ma anche dopo quel passaggio, la mappa delle intestazioni è ancora vuota

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

grazie per avermi aiutato su questo

Risposte

1 Adjunta Oct 02 2020 at 10:01

Secondo il prototipo del metodo clone (), hai una proprietà oggetto per impostare le intestazioni (denominata setHeaders)

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

Dovresti fare come segue

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