angular - 多次单击按钮时的Angular 6订阅清理
问题描述
假设我有一个订阅联系我们服务的联系我们按钮,该按钮在触发 http 请求后返回一个 observable。
如果用户点击按钮 10 次并发送 10 封电子邮件(需要),是否会同时运行 10 个订阅?如果是这样,在这种情况下订阅清理的最佳做法是什么?
解决方案
只需将您的订阅保存在属性中并检查它是否存在,不要订阅,如果不订阅,则
cacheSub: Subscription;
contactUs() {
if(!this.cacheSub) {
this.cacheSub = this.service.cacheSub.subscribe(....);
}
}
编辑
如果您想每次订阅并清理每个订阅,您可以这样做
cacheSub: Subscription;
contactUs() {
this.cacheSub = this.service.cacheSub.subscribe(() => {
// some code here if you need it
this.cacheSub.unsubscribe();
});
}
或者
contactUs() {
this.cacheSub && this.cacheSub.unsubscribe();
this.cacheSub = this.service.cacheSub.subscribe(() => {
// some code here if you need it
});
}
推荐阅读
- bash - 使用 bash 在特定列中提取具有特定值的行
- java - 如何构建包含 JAXB/Moxy 适配器的项目
- c# - 弹丸不移动,也不从玩家开始(Unity 2D / C#)
- typescript - 网格数据不显示
- javascript - 默认蜂鸣/叮/警告/警报/嗡嗡声/无声音的 Web API
- angular - 如何在按钮上选择后显示日期
- flutter - Flutter:保存和恢复列表视图的最后滚动位置不起作用
- android - 能够在完成时返回到堆栈上的最后一个活动的验证屏幕,并在后按时完成整个应用程序
- javascript - 没有父级的 JSON 文件如何获取?
- android - Android Facebook loginResult 拒绝电子邮件权限