Wait for another observable before proceeding

旧街凉风 提交于 2019-12-20 05:16:22

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/38071570/wait-for-another-observable-before-proceeding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!