angular – 无法读取未定义的属性’unsubscribe'(rxJS – 订
发布时间:2020-12-17 17:16:29 所属栏目:安全 来源:网络整理
导读:我试图抓住rxJS中的订阅和可观察量. 我想通过取消订阅来更改Observable的间隔,然后使用新的间隔设置重新订阅. 应该是非常简单,但由于我是这个领域的初学者,我可能需要一些帮助. 见这plunk export class AppComponent implements OnInit { title = 'Observabl
我试图抓住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; } ); } 在您的情况下,没有任何返回.这就是为什么你有一个未定义的错误… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |