Home > Net >  How can I get data from service in Angular interceptor?
How can I get data from service in Angular interceptor?

Time:11-02

I want to add my authentication token in request header in my auth.interceptor.ts and I'm keeping 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?

CodePudding user response:

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

  • Related