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
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 {
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