【发布时间】:2018-09-07 19:08:09
【问题描述】:
我正在构建一个带有订阅的 Angular 应用程序。该组件是一个聊天消息页面,其中有一个包含您与他人的所有聊天消息的菜单,您可以单击每个人以查看与该人的聊天消息。这是我的组件中的一个函数
getAllChatMessages() {
this.chatService
.getChatMessages(this.currentChatId, this.otherUserId)
.takeUntil(this.ngUnsubscribe)
.subscribe(userProfile => {
//some logic here
});
}
现在,每次用户单击正在与之聊天的其他人时,都会调用此 getAllChatMessages() 函数。所以在这种情况下,订阅被一遍又一遍地调用,尽管this.currentChatId 和this.otherUserId 不同。 takeUntil 只有在组件被销毁时才能取消订阅。
我真正不清楚的是旧订阅是否仍然存在,而它的另一个实例在下一个 getAllChatMessages() 调用中被实例化。由于每个订阅都拥有不同的资源,我是否应该在每次随后调用 getAllChatMessages() 时取消订阅旧订阅?
编辑:
如果我确实需要清除旧订阅,我可能正在寻找类似的东西?这样,在随后的每次通话中,我都会从 getAllChatMessages() 的最后一次通话中删除和取消订阅。
getAllChatMessages() {
if (this.getChatMsgSub) {
this.getChatMsgSub.unsubscribe();
}
this.getChatMsgSub = this.chatService
.getChatMessages(this.currentChatId, this.otherUserId)
.takeUntil(this.ngUnsubscribe)
.subscribe(userProfile => {
//some logic here
});
}
【问题讨论】:
标签: angular rxjs subscribe unsubscribe