Quiero agregar mi token de autenticación en el encabezado de solicitud en mi auth.interceptor.ts y mantengo el valor del token de autenticación en mi auth.service.ts . Aquí está auth.interceptor.ts
@Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private router: Router, private authService: AuthService) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { console.log('intercept', request); const authReq = request.clone({headers: request.headers.set(this.authService.getAuthenticationKey(), this.authService.getAuthenticationToken())}); return next.handle(request); } }y aquí hay parte de auth.service.ts
... public getAuthenticationToken(): string { return this.authenticationToken; } public getAuthenticationKey(): string { return this.authenticationKey; } ...Y aquí está mi app.module.ts
providers: [ { provide: HTTP_INTERCEPTORS, useFactory: (router: Router, authService: AuthService) => { return new AuthInterceptor(router, authService); }, multi: true, deps: [Router] } ],pero me sale este error
TypeError: Cannot read properties of undefined (reading 'getAuthenticationKey')¿Cuál es el problema?
Agregue AuthService a las dependencias ( deps ). Como la función de fábrica tiene acceso a AuthService , debe inyectarlo en el proveedor de fábrica.
providers: [ { provide: HTTP_INTERCEPTORS, useFactory: (router: Router, authService: AuthService) => { return new AuthInterceptor(router, authService); }, multi: true, deps: [Router, AuthService] } ],