'How can I get data from service in Angular interceptor?

I want to add my authentication token in the request header in my auth.interceptor.ts and I'm keeping the authentication token value in my auth.service.ts.

Here's 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);
    }
}

and here's part of auth.service.ts

...
public getAuthenticationToken(): string {
    return this.authenticationToken;
}

public getAuthenticationKey(): string {
    return this.authenticationKey;
}
...

And here's my app.module.ts

providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useFactory: (router: Router, authService: AuthService) => {
            return new AuthInterceptor(router, authService);
        },
        multi: true,
        deps: [Router]
    }
],

But I get this error:

TypeError: Cannot read properties of undefined (reading 'getAuthenticationKey')

What is the problem?



Solution 1:[1]

Add AuthService into dependencies (deps). As the factory function has access to AuthService, you need to inject it into the factory provider.

providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useFactory: (router: Router, authService: AuthService) => {
            return new AuthInterceptor(router, authService);
        },
        multi: true,
        deps: [Router, AuthService]
    }
],

References

Using factory providers

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yong Shun