我正在构建一个带有订阅的 Angular 应用程序。该组件是一个聊天消息页面,其中有一个包含您与其他人的所有聊天消息的菜单,您可以单击每个人以查看与该人的聊天消息。这是我的组件中的功能之一
getAllChatMessages() {
this.chatService
.getChatMessages(this.currentChatId, this.otherUserId)
.takeUntil(this.ngUnsubscribe)
.subscribe(userProfile => {
//some logic here
});
}
现在这个
getAllChatMessages()
每次用户单击与他们聊天的不同人时,都会调用该函数。因此,在这种情况下,尽管使用不同的 this.currentChatId
多次调用 subscribe 。和 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
});
}
最佳答案
是的 - 如果不再需要订阅,您应该取消订阅。使用 take
的示例运算符(operator):
this.chatService
.getChatMessages(this.currentChatId, this.otherUserId).pipe(take(1))
.subscribe(...)
你也不需要在销毁时清理它,因为它在第一次发射后已经死了。
关于angular - 多次调用包含订阅的方法,我应该每次都取消订阅旧订阅吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49545663/