所以我试图提高我的角度技能,而且我目前正在论坛上工作。
我有想法向用户显示目前有多少用户在线。当他们进入网站的论坛部分时,我更新了我的数据库,将一个成员添加到计数中,当他们离开时,它会从同一个数据库中扣除一个。
当我向ngOnInit()和ngOnDestroy中添加了一个加号逻辑时,我认为我已经想到了这一切,但后来我注意到当我用f5刷新页面时,ngOndestroy()没有&被解雇了。结果是它不断地将成员添加到成员计数中,即使它始终是查看页面的同一个人。
当用户导航到我的SPA的另一部分以及刷新页面时,如何确保计数扣除一个?
我的代码:在ngOnDestroy中我执行服务器请求以在数据库中扣除一个,然后取消订阅组件中的所有可观察项
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();
})
}
答案 0 :(得分:8)
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();
})
}