简体   繁体   English

只运行一次 observables,然后检查是否完成 - angular2 typescript

[英]Only run observables once, then check if completed after - angular2 typescript

Very new to Observables so apologies if this is basic, but i have tried googling, and dont seem to be able to find what i want. Observables非常新,所以很抱歉,如果这是基本的,但我尝试过谷歌搜索,但似乎无法找到我想要的。

Here is an example plunkr, very basic.这是一个示例 plunkr,非常基本。
https://plnkr.co/edit/kgECPQyoKqY7RamebUUu?p=preview https://plnkr.co/edit/kgECPQyoKqY7RamebUUu?p=preview

Why is my Initialized method not called until my service calls it?为什么我的Initialized方法直到我的服务调用它才被调用? I thought that the initialized observable would be executed as soon as i do Observable.forkJoin ??我认为initialized observable 会在我执行Observable.forkJoin立即执行? Do i need to start the process somehow?我需要以某种方式开始这个过程吗?

And why my myService.loadOtherData method never seems to call the subscribe method???为什么我的myService.loadOtherData方法似乎永远不会调用 subscribe 方法???

Thanks in advance提前致谢

If you're very new to Observables, i suggest you start with a basic example.如果您对 Observables 非常陌生,我建议您从一个基本示例开始。

For example: (pseudo-code, maybe)例如:(伪代码,也许)

let observable = new Observable<string>(observer => {
  if (1 == 1) {
    observer.next("one is one");
  } else {
    observer.error("one is not one");
  }
});
observable.subscribe(
  response => console.log(response), 
  error -> console.log(error)
);

Using a subject is more of the same but a Subject can be used a little more freely:使用主题更相似,但主题可以更自由地使用:

let subject = new Subject();
subject.subscribe(response -> console.log(response));
subject.next('hello');

I believe i saw you combinding the two, subscribing to the subject then getting data with an observable?我相信我看到您将两者结合起来,订阅主题然后使用可观察对象获取数据? With these examples, do you have enough information or do you need a very specific example?有了这些例子,你有足够的信息还是需要一个非常具体的例子?

edit:编辑:

your this.initialized.subscribe 'starts the process'.你的this.initialized.subscribe '开始这个过程'。 You call the loadOtherData function too late, which makes you NOT subscribed to this.initialized when the data returns.您太晚调用 loadOtherData 函数,这使您无法在数据返回时订阅 this.initialized。 That's why you don't see console.log('initialized')这就是为什么你看不到 console.log('initialized')

edit2:编辑2:

Take note that a BehaviorSubject holds it's data and returns it on subscribe.请注意BehaviorSubject保存它的数据并在订阅时返回它。 There is no need to initialize it with an empty string.不需要用空字符串初始化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM