Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

I have added this code into my app.module.ts

    providers: [ AppConfigService,
            {
                provide: APP_INITIALIZER,
                useFactory: (config: AppConfigService) => () => config.getAppConfig(),
                deps: [AppConfigService],
                multi: true
            },
]

Getting this error

enter image description here

Issue: i have used ngx-permission pkg for permission. i set route permission method. but when i refresh a page that time redirect on home page instead stay on current page. so i tried to load permissions before application start up method for resolve this issue but got this error.

 config.getAppConfig() // call when application start up

have any idea please help. other solution also welcome.

like image 321
Shailesh Ladumor Avatar asked Sep 27 '17 06:09

Shailesh Ladumor


2 Answers

This error can happen when the dependencies in your APP_INITIALIZER have a dependency on an Angular service, e.g. Router.

The solution is lazy injection by changing the constructor of your service to accept a Injector instead, and then resolve the value outside the constructor.

Example AppConfigService:

import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

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

  // Helper property to resolve the service dependency.
  private get _router() { return this._injector.get(Router); }

  constructor(
    //private _router: Router
    private _injector: Injector
  ) { }

  navigate() {
    this._router.navigate(['/']);
  }
}
like image 117
Bart Verkoeijen Avatar answered Oct 02 '22 18:10

Bart Verkoeijen


i had fixed my issue with this solution

create function into app.module.ts

export function loadConfig(appService: AppConfigService): Function {
    return () => appService.getAppConfig();
}

 AppConfigService,
        {
            provide: APP_INITIALIZER,
            useFactory: loadConfig,
            deps: [AppConfigService],
            multi: true
        },

issue into `HttpInterceptor` so i used injector for that
constructor(private inj: Injector) {
        super(
            inj.get(XHRBackend),
            inj.get(RequestOptions)
        );
}
like image 44
Shailesh Ladumor Avatar answered Oct 02 '22 18:10

Shailesh Ladumor