ngOnDestroy不破坏localStorage令牌 [英] ngOnDestroy not destroying localStorage token

查看:72
本文介绍了ngOnDestroy不破坏localStorage令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在应用程序级别而不是组件级别利用ngOnDestroy?

How can I leverage ngOnDestroy at the application level and not at the component level?

我想在用户关闭我的应用程序时执行以下代码.

I want to execute the following code when the user closes my application.

ngOnDestroy(): void {
    localStorage.removeItem('token');
}

我像这样将其放入 AppComponent 中:

export class AppComponent implements OnDestroy {
     ngOnDestroy(): void {
         localStorage.removeItem('token');
     }
}

关闭应用程序时,似乎未触发 OnDestroy .在这种情况下,我通过检查令牌并重定向到登录页面(如果不存在)来使用本地存储中的令牌来确定用户是否已登录.如果在关闭应用程序时未销毁令牌,则这显然不起作用.

The OnDestroy does not seem to fire when the application is closed. In this case I'm using the token in local storage to determine if the user has logged in or not by checking for the token and redirecting to the login page if it doesn't exists. This obviously doesn't work if the token isn't destroyed when the application is closed.

在哪里可以放置此代码以获取所需的行为,或者有更好的方法来完成我要完成的工作?

Where can I place this code to get the behavior I'm looking for, or is there a better way to accomplish what I'm trying to accomplish?

推荐答案

那是行不通的.Angular永远不会自行删除根组件.您可能需要类似窗口中所述的内容.onbeforeunload和window.onunload在Firefox,Safari和Opera中不起作用?

That can't work. Angular never removes the root component by itself. You would need something like explained in window.onbeforeunload and window.onunload is not working in Firefox , Safari , Opera?

这篇关于ngOnDestroy不破坏localStorage令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆