angular - 无法读取未定义的属性 'unsubscribe'(rxJS - 订阅)

标签 angular rxjs observable

我正在尝试掌握 rxJS 中的订阅和可观察对象。

我想通过取消订阅来更改 Observable 的间隔,然后使用新的间隔设置重新订阅。

应该非常简单,但由于我是这方面的初学者,我可能需要一些帮助。

查看此 plunk

export class AppComponent implements OnInit {
  title = 'Observable Interval - Changing interval';
  currentTime: any;
  refreshInterval: number = 1000;
  private subscription: Subscription;

  constructor(private timeService: TimeService) {
  }

  clicked($event) {
    console.log('new refreshInterval: ' + this.refreshInterval);

    // Here I would like to unsubscribe to the subscription 
    // and then resubscribe using the new interval. 
    // However using below statement causes a 
    // TypeError: Cannot read property 'unsubscribe' of undefined
    this.subscription.unsubscribe();
    this.getTime();
  }

  // with this implementation changing the refreshInterval won't have any affect. 
  getTime() {
            this.timeService.getTime(this.refreshInterval)
              .subscribe(t => {
                this.currentTime = t;
              }
            );
    }

  ngOnInit() {
    this.subscription = this.getTime();
    console.log(this.subscription);
    console.log('refreshing each ' + this.refreshInterval + ' ms');
  }
}

最佳答案

您需要在 getTime 方法中返回订阅:

getTime() {
  return this.timeService.getTime(this.refreshInterval) // <-----
          .subscribe(t => {
            this.currentTime = t;
          }
        );
}

在您的情况下,没有返回任何内容。这就是为什么你有一个未定义的错误......

关于angular - 无法读取未定义的属性 'unsubscribe'(rxJS - 订阅),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37482224/

相关文章:

javascript - 在 localStorage 中存储对象

javascript - 主题与匿名主题

angular - 如何对 combineLatest 中的每个函数进行单独的错误处理?

javascript - 在 Angular 2+ 中按顺序订阅可变数量的 Observable

angular - 错误响应中断 valueChanges [Angular2]

javascript - 如何使用 ngrx 状态管理编辑表单数据?我得到错误(尝试比较错误 '[object Object]' 。仅允许数组和迭代”))

angular - 分派(dispatch)新操作时,如何避免通过循环存储对象而重新渲染组件

Angular(7) 扩展原理图

reactive-extensions-js - 将 RxJS Observable 收集到数组

knockout.js - 如果值在外部发生变化,则未检测到 knockout 可观察到的变化