Angular 9 - mecanografiado - headers.set - sin agregar encabezado

Oct 02 2020

Intento usar un inyector angular para agregar un token de portador

aunque se ejecuta el código, no se agrega el encabezado

hay muchos códigos diferentes, probé algunos de ellos, todos conducen al mismo problema

no se envía ningún portador con la solicitud

en la imagen de abajo me detuve en clone / headers.set , pero incluso después de ese paso, el mapa de encabezados todavía está vacío

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

gracias por ayudarme en este

Respuestas

1 Adjunta Oct 02 2020 at 10:01

De acuerdo con el prototipo del método clone (), obtuvo una propiedad de objeto para establecer encabezados (llamado setHeaders)

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

Deberías hacer lo siguiente

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