1

I don't know if I should post any code for this. But I will if required. I have an Angular2 directive, MyDirective and a service MyService

The service makes an http call in its constructor to fetch something and store in say this.list.

Directive injects the service and uses it as myService.isPresent(item).

Now, the problem is that by the time directive executes, the http call for fetching the list in the service isn't completed. Is there a clean way to make the directive wait till the service is ready?

0

1 Answer 1

2

No, since the http calls are always asynchronous you can't synchronously wait for them.

You can however instantiate the service with the ReflectiveInjector yourself and call the initialization before bootstrapping your app to be sure everything has loaded.

In the bootstrap call just provide your MyService instance with the data.

//import ... from ... import {MyService} from './my.service'; let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS, MyService]); var myService: MyService = injector.get(MyService); myService.init() .subscribe(data => { bootstrap(App, [ HTTP_PROVIDERS, provide(MyService, {useValue: myService}) ]) .catch(err => console.error("error: ", err)); }); 

In your MyService add this init method returning an Observable for your data loading:

init(): Observable<any> { if (!this._initialized) { this._initialized = true; return this._http.get(this._url) .map(data => { this._data = data.json(); return this._data; }); } else { console.log("Already initialized!"); } } 

Plunker with a working example

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

4 Comments

But then this will result in multiple http requests right? How can I only make one http request and prevent all subsequent loadData calls to ignore (but give them callback once the first call gets completed)
So the data stays the same for the whole runtime?
Yes, its just an initial call to fetch and cache. May be there's a better approach?
Okay, so I tried and built something which solves your problem. Going to update my answer in a minute.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.