等待其他可观察到的内容,然后继续 [英] Wait for another observable before proceeding

查看:48
本文介绍了等待其他可观察到的内容,然后继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否应该为此发布任何代码.但是如果需要,我会的.我有一个Angular2指令MyDirective和服务MyService

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

该服务在其构造函数中进行http调用以获取内容并将其存储在诸如this.list的位置.

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

指令注入服务并将其用作myService.isPresent(item).

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

现在,问题在于,通过执行time指令,用于获取服务中列表的http调用未完成.有没有一种干净的方法可以让指令等待服务准备就绪?

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?

推荐答案

否,由于http调用始终是异步的,因此您无法同步等待它们.

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

但是,您可以自己使用ReflectiveInjector实例化服务,并在引导应用程序之前调用初始化,以确保一切都已加载.

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

bootstrap调用中,只需为您的MyService实例提供数据.

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));
  });

在您的MyService中添加此init方法,以返回Observable进行数据加载:

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

这篇关于等待其他可观察到的内容,然后继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆