javascript - ngOnDestroy 不会在页面重新加载时触发
问题描述
所以我正在努力提高我的角度技能,我目前正在一个论坛上工作。
我的想法是向用户展示当前有多少用户在线。当他们进入网站的论坛部分时,我更新我的数据库以将一名成员添加到计数中,当他们离开时,它会从同一个数据库中扣除一个。
当我将加一逻辑添加到 ngOnInit() 并将减一逻辑添加到 ngOnDestroy 时,我以为我已经明白了,但后来我注意到当我用 f5 刷新页面时,ngOndestroy() 没有触发. 结果是它不断地将成员添加到成员计数中,即使它始终是同一个人查看页面。
当该人导航到我的 SPA 的另一部分以及刷新页面时,我如何确保计数减去一个?
我的代码:在 ngOnDestroy 中,我执行服务器请求以在数据库中扣除一个,然后取消订阅组件中的所有 observables
export class ForumCountComponent implements OnInit, OnDestroy{
data;
ngUnsubscribe = new Subject();
constructor(private authService: AuthenticationService, private forumService: ForumService){
}
ngOnInit(){
let loggedIn = this.authService.isLoggedIn();
this.forumService.forumCountPlus(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
console.log(data);
})
}
ngOnDestroy(){
let loggedIn = this.authService.isLoggedIn();
this.forumService.forumCountMin(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
})
}
解决方案
ngOnDestroy
仅当组件在角度工作流程内被销毁时才会触发。但是,刷新页面不在工作流范围内,因此不会触发此方法。要在用户离开/刷新页面时处理操作,您需要使用onbeforeunload。
ngOnInit(){
let loggedIn = this.authService.isLoggedIn();
this.forumService.forumCountPlus(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
console.log(data);
})
window.onbeforeunload = () => this.ngOnDestroy();
}
ngOnDestroy(){
let loggedIn = this.authService.isLoggedIn();
this.forumService.forumCountMin(loggedIn)
.takeUntil(this.ngUnsubscribe)
.subscribe((data) => {
this.data = data;
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
})
}
推荐阅读
- ios - 在 SwiftUI 中从 ViewModel 访问 EnvironmentObject
- java - 如何以编程方式更改 Android Toggle/LabeledSwitch 边框颜色?
- c++ - WaitCommTimeout() 错误87“参数无效”等事项
- arrays - RPG YAJL 解析数组内的数组
- javascript - axios - 从 url 获取 gz 信息
- python - 给定一个以字符串列表为值的字典,您将如何检索列表中包含对所有其他列表唯一的字符串的所有键?
- git - Git diff 没有显示不同分支上的文件之间的绝对差异(所有提交的原始差异)
- asp.net - 解析器错误消息:无法加载类型“PatronWebUserUtility.PatronWebUserMaintenance”
- reactjs - 可重复使用的活动/非活动单选按钮未传递值
- javascript - For循环不检查数组中的所有元素