Angular 2: Call service before bootstrap

后端 未结 1 1248
南方客
南方客 2021-01-28 09:21

When bootstrapping my Angular 2 (v2.4) I am trying to run a function which will automatically authorise the user before the application loads. However, this does not seem to be

1条回答
  •  南方客
    南方客 (楼主)
    2021-01-28 09:44

    Add the services it depends on to the provider list you already have.

    ...
    platformBrowserDynamic().bootstrapModule(AppModule, {
         providers: [ UserRepository, SessionManager, HttpModule,
        {
            provide: APP_INITIALIZER,
            useFactory: auth,
            deps: [UserRepository, SessionManager, HttpModule],
            multi: true
        }
    ]});
    ...
    

    https://github.com/angular/angular/blob/4.0.0/packages/core/src/linker/compiler.ts#L90-L109

    for compiler options you provide an object that has providers on it. This should now compile with it understanding the classes you want to use for the factory.

    As a note you could also do this in your appmodule in its provider list instead of doing it on the bootstrap compiler options

    0 讨论(0)
提交回复
热议问题