RxJs:如何“倾听”在订阅接收到流时对其进行更改

RxJs: How to "listen" to change on a subscription when it receives a stream?

本文关键字:如何 倾听 RxJs      更新时间:2023-09-26

我是Angular 2和Observables的新手,但是我还没有找到一种方法来"监听"订阅接收到流时的变化,我甚至不知道这是否可能或者是否是正确的方法。

我以前是这样对待承诺的:

// Constructor and more code
// ...
ngOnInit(): void {
  this.loading.present();
  this.getItems()
      .then(() => this.loading.dismiss());
}
getItems(): Promise {
  return this.itemService
    .getItems()
    .then(items => this.items = items);
}
refresh(refresher): void {
  this.getItems()
      .then(() => refresher.complete());
}

我已经尝试过订阅/观察,但我只是不知道如何:

// Constructor and more code
// ...
ngOnInit(): void {
  this.loading.present();
  this.getItems()
      .subscribe(() => this.loading.dismiss());
}
getItems(): Subscription {
  return this.itemService
    .getItems()
    .subscribe(items => this.items = items);
}
refresh(refresher): void {
  this.getItems()
      .subscribe(() => refresher.complete());
}

当然,我得到一个编译错误:Property 'subscribe' does not exist on type 'Subscription',任何帮助如何实现这与可观察对象(RxJS)?

Subscription是侦听器,你不能听侦听器,对吗?

相反,您需要返回一个Observable以便能够订阅。将你的函数修改如下(未测试):

getItems(): Observable<any> {
  let obs = this.itemService.getItems().share();
  obs.subscribe(items => this.items = items);
  return obs;
}