首页 > 解决方案 > 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();
            })
    }

标签: javascriptangular

解决方案


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();
        })
}

推荐阅读