2

In my Angular2 application I need to make a call to some function from AuthenticationService and bootstrap application based on results of this call. The problem is that AuthenticationService has dependency on HTTP from @angular/http and I have very little idea of how to build http service manually before calling bootstrap function. Accepted answer in this question angular2 bootstrap with data from ajax call(s) describes what I want to achieve perfectly, but unfortunately it was given to some previous version of Angular2.

I tried to create http service this way:

let injector = ReflectiveInjector.resolveAndCreate(HTTP_PROVIDERS)
let http = injector.get(Http);

but I got null reference exception in XsrfCookieStrategy or something like that. I believe it is possible to inject some empty XsrfStrategy, but it seems to be more like a hack than a good solution. So the question is: are there any good (official) way to bootstrap Angular2 application with providing some dependencies up-front similar to the link I added above.

Community
  • 1
  • 1
  • 1
    You could bootstrap a component that just does the ajax call and have it bootstrap your real component... Really though you might just want to program your main component so it can display a state for your application before the call as well and makes the call itself. – Jason Goemaat Aug 01 '16 at 20:24
  • Jason, I think I can see what you mean here, but are there any examples or code that illustrate the idea of app built this way? The code I want to run at a bootstrap is the main and only entry point, so it should be executed at any route (url) even before such thing as route becomes a thing. So I wonder what is the proper angular way to do it. I thought that placing this code in bootstrap.ts file would be a good idea – Alexander Romanov Aug 01 '16 at 20:38
  • I haven't found a "best way" to do this yet, I kinda have the same problem. That's why I posted a comment instead of an answer, there could be a better way to do it. What you could do it have a "ParentComponent" that you bootstrap and that does the initial API call and just have it include your main component with an ngIf for when your initial call is complete `` – Jason Goemaat Aug 01 '16 at 23:22

1 Answers1

1
class AuthService {
  isLoggedIn:BehaviorSubject<boolean> = BehaviorSubject<boolean>(false);
  checkLogin(http:Http) {
    return http.get(...)
    .map(result => result.json())
    .do(result => this.isLoggedIn.next(result)
  }
}

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  AuthService,
  { provide: APP_INITIALIZER, 
    useFactory: (authService:AuthService) => authService.checkLogin(),
    deps: [AuthService],
    multi: true
  }
]);

See also How to pass parameters rendered from backend to angular2 bootstrap method

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567