10

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 ?

Scipion
  • 11,449
  • 19
  • 74
  • 139

3 Answers3

12

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.

Hardik Patel
  • 3,868
  • 1
  • 23
  • 37
4

What I was trying to do isn't feasible since the APP_INITIALIZER happens before the router init. https://medium.com/hackernoon/hook-into-angular-initialization-process-add41a6b7e

Bart Verkoeijen
  • 16,545
  • 7
  • 52
  • 56
Scipion
  • 11,449
  • 19
  • 74
  • 139
  • 2
    Depending on your needs you could use APP_BOOTSTRAP_LISTENER: https://angular.io/api/core/APP_BOOTSTRAP_LISTENER – sorohan Feb 09 '18 at 09:52
  • 1
    The link is dead. This seems to be the same article: https://medium.com/hackernoon/hook-into-angular-initialization-process-add41a6b7e – reduckted Sep 27 '19 at 03:07
2

As another answer pointed out, the APP_INITIALIZER is triggered before the router initializes. In this scenario, you can simply use window.location.pathname, or any other properties under window.location.

Aaron Eads
  • 63
  • 4