Injector Error “Provider parse errors: Cannot instantiate cyclic dependency!”

前端 未结 3 1990
一整个雨季
一整个雨季 2021-01-02 13:37

I tried to create an HttpInterceptor to add some headers for authorization to every http that happens. I need to get the headers from a service called

相关标签:
3条回答
  • 2021-01-02 13:58

    Remove AuthService from providers list as it is imported in the Interceptor already thus the cyclic dependency.

    0 讨论(0)
  • 2021-01-02 14:00

    Look at this GitHub Discussion (Issue #18224)

    As a workaround you can use Injector manually and inject relevant service inside intercept method: https://github.com/angular/angular/issues/18224#issuecomment-316957213

    I resolved simply not setting authService in constructor but getting in the intercept function.

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Get the auth header from the service.
        const auth = this.inj.get(AuthenticationService);
        const authToken = auth.getAuthorizationToken();
        ...
    }
    

    UPDATE:

    Prior to Angular 4.3.0 unfortunately it's impossible to use Injector manually inside intercept method:

    ERROR Error: Uncaught (in promise): RangeError: Maximum call stack size exceeded

    So there is one more workaround using rxjs:

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return Observable.create((observer: any) => {
            setTimeout(() => {
                const authService = this.injector.get(AuthenticationService)
                observer.next(authService.getAuthorizationHeader())
                observer.complete()
            })
        })
            .mergeMap((Authorization: string) => {
                let authReq = req
    
                if (Authorization) {
                    authReq = req.clone({
                        setHeaders: {
                            Authorization
                        }
                    })
                }
    
                return next.handle(authReq)
            })
    }
    
    0 讨论(0)
  • 2021-01-02 14:08

    Remove following from AuthService -

    import { HttpClient } from '@angular/common/http';
    

    The reason is - HttpClient using interceptor internally and interceptor using AuthService and AuthService is using HttpClient. thus it gives "cyclic dependency" error.

    0 讨论(0)
提交回复
热议问题