Angular 9 - typescript - headers.set - başlık eklememe

Oct 02 2020

Taşıyıcı jeton eklemek için açısal bir enjektör kullanmaya çalışıyorum

kod yürütülmesine rağmen başlık eklenmez

Orada birçok farklı kod var, bazılarını denedim, hepsi aynı soruna yol açıyor

istek ile taşıyıcı gönderilmez

aşağıdaki resimde clone / headers.set'de durdum , ancak bu adımdan sonra bile üstbilgi haritası hala boş

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

bana bu konuda yardım ettiğin için teşekkürler

Yanıtlar

1 Adjunta Oct 02 2020 at 10:01

Clone () yöntemi prototipine göre, üstbilgileri ayarlamak için bir nesne özelliğiniz var (setHeaders olarak adlandırılır)

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

Aşağıdaki gibi yapmalısın

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