【问题标题】:RxJs: How to "listen" to change on a subscription when it receives a stream?RxJs:接收流时如何“监听”订阅的变化?
【发布时间】:2017-01-20 11:58:39
【问题描述】:

我是 Angular 2 和 Observables 的新手,但我还没有找到一种方法来“监听”接收到流时订阅的更改,我什至不知道这是否可能,或者它是否是正确的方式。

这就是我以前对 Promise 所做的:

// 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',关于如何使用 Observables (RxJS) 实现这一点的任何帮助?

【问题讨论】:

    标签: javascript angular rxjs observable angular2-http


    【解决方案1】:

    Subscription 是一个听众,你不能听一个听众,可以吗?

    相反,您需要返回 Observable 才能订阅。将您的功能更改为如下(未测试):

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

    【讨论】:

    • 非常感谢!我知道我做错了,我只是不知道如何做对
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    相关资源
    最近更新 更多