如何在间隔上获取端点,停止间隔,并在离开页面时中止调用



在上一次调用成功后,我每秒都会获取消息。问题是,有时需要2秒钟才能完成呼叫。在那段时间里,我可以导航回来,选择另一个人,并与他展开对话。

现在,上一次调用成功,并使用来自UserA和UserB的会话数据填充该区域。此外,它不断获取用户A和用户B的对话。

我怀疑也许我应该使用clearTimeout(interval)而不是clearTimeout(fetchConversationInterval),或者使用更好的代码?

但是,如果用户在获取消息时导航回来,我如何中止仍未完成的调用?

我有以下代码:

在数据中((

fetchConversationInterval: null,

装载时((:

this.messagesFetchingInterval()

并且在destroy((之前

clearTimeout(this.fetchConversationInterval)

方法:

async messagesFetchingInterval () {
let that = this
this.fetchConversationInterval = setTimeout(async function interval () {
await that.getConversation(that.peerProfile.user_id)
.finally(()=> {
if (that.currentRoute === '/direct-messages/conversation') {
that.fetchConversationInterval = setTimeout(interval, 1000)
}
})
}, 1000)
},

异步函数(在您的例子中是getConversation(返回它们的订阅。您可以将其保存在参数中,然后在destroy中取消订阅。

var mySubscription;
this.mySubscription = someAsyncFunc().subscribe((result) => {
console.log(result);
})
ngOnDestroy(){
this.mySubscription.unsubscribe();
}

最新更新