JT-Helsinki
JT-Helsinki

Reputation: 391

Angular 2: Call service before bootstrap

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 working.

import {platformBrowserDynamic} from "@angular/platform-browser-dynamic";
import {enableProdMode, APP_INITIALIZER} from "@angular/core";
import {Http, HttpModule} from "@angular/http";
import {PARAMETERS} from "../config/parameters";
import {AppModule} from "./AppModule";
import {UserRepository} from "../modules/service/repository/UserRepository";
import {SessionManager} from "../modules/service/manager/SessionManager";


export function auth(userRepository: UserRepository) {
    console.log("BOOM!");
    return () => userRepository.autoAuthorize();
};

platformBrowserDynamic().bootstrapModule(AppModule, [
    {
        provide: APP_INITIALIZER,
        useFactory: auth,
        deps: [UserRepository, SessionManager, HttpModule],
        multi: true
    }
])
    .catch(err => console.error(err));

What am I doing wrong and how can I get it working? Also, if I have this code as above, do I need to add these services to my providers array in the AppModule?

Many thanks

JT

Upvotes: 1

Views: 3427

Answers (1)

KeniSteward
KeniSteward

Reputation: 179

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

Upvotes: 1

Related Questions