Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8: Cannot instantiate cyclic dependency - ActivatedRoute

I am trying to integrate the APP_INITIALIZER from Angular in my project in order to do some functionalities before start the application. The problem comes when I use the ActivatedRoute from Angular in my service.

The error is:

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

I suppose that I am using some import twice internally or something like this. Basically i tried with some other configurations but at the end always is throwing me the same error.

STACKBLITZ EXAMPLE: https://stackblitz.com/edit/angular-bhpe7m

Expected behavior: Just to be able to retrieve some QueryParams by the ActivatedRoute service and do some functionality with them before run the Angular app

like image 469
Jgascona Avatar asked Jul 25 '19 15:07

Jgascona


2 Answers

Make sure to include HttpClientModule in your app.module.ts

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

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      AppRoutingModule,
      HttpClientModule
   ],
})
export class AppModule { }
like image 68
Suraj Parise Avatar answered Sep 20 '22 14:09

Suraj Parise


Got your problem just remove router from your 'appLoaderService'

  constructor(private route: ActivatedRoute) {} // remove this dependency

You are getting cyclic dependency since you are injecting route in the config which initializes your app.

Refer this

Simply, remove this since you are not using it anyways.

However if you indent to use route before your bootstrapping component loads, you can go for resolver or guards.

As mentioned, it is not possible to use routes inside APP_INITIALIZER, *though there is a way**, but i would better suggest to use Resolver as following:

resolve(route: ActivatedRouteSnapshot): Promise<any> {
    const promise = new Promise((resolve, reject) => {
      if (route) {
        console.log(route.params);
        console.log(route.queryParams);
      }
 }
return promise;
}

Resolver for reference

EDIT Here is what you will have after placing code in resolver :

enter image description here

like image 43
yanky_cranky Avatar answered Sep 18 '22 14:09

yanky_cranky