Angular 4 Injecting route in the APP_INITIALIZER
Asked Answered
C

3

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 ?

Chickabiddy answered 19/10, 2017 at 14:37 Comment(2)
can you create a reproducible problem on stackblitz?Jimerson
Cheers mate, that should be the accepted answerChickabiddy
C
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

Chickabiddy answered 23/10, 2017 at 11:19 Comment(2)
Depending on your needs you could use APP_BOOTSTRAP_LISTENER: angular.io/api/core/APP_BOOTSTRAP_LISTENERAnglophobe
The link is dead. This seems to be the same article: medium.com/hackernoon/…Prosector
A
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.

Abbacy answered 23/8, 2018 at 6:46 Comment(0)
C
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

Chickabiddy answered 23/10, 2017 at 11:19 Comment(2)
Depending on your needs you could use APP_BOOTSTRAP_LISTENER: angular.io/api/core/APP_BOOTSTRAP_LISTENERAnglophobe
The link is dead. This seems to be the same article: medium.com/hackernoon/…Prosector
P
1

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.

Pyrognostics answered 20/7, 2022 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.