Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Injecting route in the APP_INITIALIZER

Tags:

angular

I am trying to retrieve a data present in the url in my APP_INITIALIZER

app.module.ts

export function init(config: ConfigService, router: Router) {
    return () => config.load(router);
}


providers : [
    ...
    {
      provide: APP_INITIALIZER,
      useFactory: init,
      deps: [ConfigService, Router],
      multi: true
    },
    ConfigService 
    ... 
]

config-service.ts

@Injectable()
export class ConfigService 
    load(router: Router): Promise<any> {
        console.log('current url : ' + router.url);
        return new Promise(((resolve, reject) => resolve()));
    }
}

Unfortunately I am getting

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

I also tried using the Injector in the constructor but it didn't work either.

Is what I am trying to do even feasible ?

like image 903
Scipion Avatar asked Oct 19 '17 14:10

Scipion


People also ask

When is the app_initializer run in angular?

As mentioned earlier, the APP_INITIALIZER is run when the application is initialized. The Angular suspends the app initialization until all the functions provided by the APP_INITIALIZER are run. If any of those intializers return a promise, then the angular waits for it to resolve, before continuing with the App initialization

What is the use of injector in angular router?

With this, we can use the Injector service to get a handle to the Angular Router, reset the config, and pass in a filtered set of routes. The Injector is used since you would otherwise get a circular reference by attempting to inject the Router.

Why does angular wait for a promise to resolve before initialization?

The Angular suspends the app initialization until all the functions provided by the APP_INITIALIZER are run. If any of those intializers return a promise, then the angular waits for it to resolve, before continuing with the App initialization

How do I inject appinitservice into initializeapp1?

But our initializeApp1 is a function and needs AppInitService to be injected as the argument. We do that by using the deps: flag and let angular know that it needs to create a instance of AppInitService and inject it to the initializeApp1 function.


1 Answers

config-service.ts can be rewritten as below.

@Injectable()
export class ConfigService
    constructor(private injector: Injector){}

    load(): Promise<any> {
        const router = this.injector.get(Router);
        console.log('current url : ' + router.url);
        return new Promise(((resolve, reject) => resolve()));
    }
}

No need to inject Router as a dependency in app.module.ts.

like image 125
Hardik Patel Avatar answered Oct 02 '22 01:10

Hardik Patel