【问题标题】:Cannot read property 'unsubscribe' of undefined (rxJS - Subscription)无法读取未定义的属性“取消订阅”(rxJS - 订阅)
【发布时间】:2016-05-27 11:23:39
【问题描述】:

我正在尝试掌握 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');
  }
}

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-23
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多