Angular 4: Cannot Instantiate Cyclic Dependency! Injectiontoken_Http_Interceptors

Angular 4: Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS

Cyclic dependency, means circling around endless, like planets orbiting sun..

Solution: Break the dependency chain, Re-factor code.

You have GlobalFunctionService -> PersonService -> so on... -> ResponseInterceptorService -> and back to -> GlobalFunctionService.

Cycle complete.

REMOVE the PersonService dependency from GlobalFunctionService. (its not used anyway, if you need it then find different way to get around.)

      import { PersonService } from 'app/shared/services/api-services/person/person.service';
import { Injectable } from '@angular/core';
import { InputModalComponent } from 'app/shared/components/input-modal/input-modal.component';
import { MatDialog } from '@angular/material';

@Injectable()
export class GlobalFunctionService {

constructor(
public dialog: MatDialog
) { }

relogin(): void {
let dialogRef = this.dialog.open(InputModalComponent, {
width: '250px',
data: { title: "Please provide your password to re-login." }
});

dialogRef.afterClosed().subscribe(result => {
debugger
console.log('The dialog was closed');
let password = result;
});
}
}

Cannot instantiate cyclic dependency! HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule CoreModule

Try not setting CrossDomainService in constructor but getting in the intercept function

@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {


constructor(private injector: Injector) {

}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// try to call the service here.
language: string = 'en';
const lanaguageInj= this.injector.get(CrossDomainService);
const globalLanguage= auth.globalLanguage.subscribe((language) => {
this.language = language;
});

const request = req.headers.has('Accept-Language') ?
req :
req.clone({ setHeaders: { 'Accept-Language': this.language } });

return next.handle(request);
}
}

Injector Error "Provider parse errors: Cannot instantiate cyclic dependency!"

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

Cannot instantiate cyclic dependency! AuthService ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

Cyclic dependency, means circling around endless, like planets orbiting sun..

Solution: Break the dependency chain, Re-factor code.

remove AuthService from the dependency of AuthService (its not used anyway, if you need it then find different way to get around.)

change:

constructor(private userService:UserService,
private afAuth: AngularFireAuth,
private auth:AuthService,
private route:ActivatedRoute) {

this.user$ = afAuth.authState;
}

to:

constructor(private userService:UserService,
private afAuth: AngularFireAuth,
private route:ActivatedRoute) {

this.user$ = afAuth.authState;
}

Angular 9: interceptor cyclic dependency while injecting lazy loaded service

Your LanguageService should not be added to the providers of the lazy loaded module. It should not be added to any providers array of a module. It should have a providedIn: 'root' in the decorator:

@Injectable({ providedIn: 'root' })
export class LanguageService {}

// lazy loaded module
imports: [
SharedModule
]

// ....
providers: []

Interceptors on the other hand, should either be declared in your core module, which is included in the App root once. Or in a lazy loaded module, to define a interceptor just for that lazy loaded module


You should restructure your application. Split up your SharedModule to -only- (!important) include components/pipes/directives. These are things that should go in a SharedModule. What -definitely- should not go in there, are application related services and imports.

By the looks of it, your SharedModule should be a CoreModule, and only be imported (not exported) in your AppModule. You should -not- import this module in a lazy loaded module. In your case it will redeclare the HttpClientModule -without- the interceptors, because they are declared in the root and not in the lazy module, making you have the issues you're facing.

Angular itself has a good overview of what kind of modules there are, and what they should and should not contain, and where they should be or should not be imported:

There are five general categories of feature modules which tend to fall into the following groups:

  • Domain feature modules.
  • Routed feature modules.
  • Routing modules.
  • Service feature modules.
  • Widget feature modules.


Related Topics



Leave a reply



Submit