4

I am currently building an Angular 2 component library so that future UI projects can share code that implements standard features. One of my requirements is these UI apps need some data from the server when they start up. I wanted to encapsulate this inside my library.

So when I inject a service from my library into my app I would like to perform an http call to a server endpoint to get some configuration. This could happen upon instantiation.

I am not sure if this is a good idea or not, will the Angular 2 bootstrap routine wait for injected services to complete the http calls?

I have seen a couple different ways to asynchronously bootstrap an Angular 2 app but I do not want to have this code inside my app but rather stay inside my library. I am trying to hide the details of this process inside my library so other developers will not attempt to hack on it.

1 Answer 1

3

You could leverage the APP_INITIALIZER service. With it, the application will wait for the returned promise to be resolved before actually starting.

Here is a sample:

provide(APP_INITIALIZER, {
  useFactory: (service:SomeService) => () => service.init(),
  deps:[GlobalService, HTTP_PROVIDERS], multi: true
})

The init method would like something like that:

init():Promise<Site> {
  var promise = this.http.get('config.json').map(res => res.json()).toPromise();
  promise.then(config => this.devServer = config.devServer);
  return promise;
}

See this issue on github for more details:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.