【问题标题】:Angular and Local Storage in strict mode严格模式下的 Angular 和本地存储
【发布时间】:2021-11-13 07:23:14
【问题描述】:

我正在使用 Angular 12,它会自动为您的项目添加严格模式。我正在通过教程在我的项目中设置身份验证,但严格模式不允许我像教程中那样设置它。我正在阅读本教程...https://www.positronx.io/full-angular-7-firebase-authentication-system/

这行代码不行……

JSON.parse(localStorage.getItem('user'));

我的文本编辑器似乎喜欢这种替代方式...

JSON.parse(localStorage.getItem('user') || '{}');

但是,该替代行似乎无法按照教程的预期工作。比如……

如果我使用这个 getter 函数来检查用户是否登录,它会返回 true。即使没有人登录。

get isLoggedIn(): boolean {
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        return (user !== null) ? true : false;
    }

所以我在这里有点迷路,正在寻找一种在严格模式下使用 localStorage 的方法。我知道我可以简单地禁用 Angular 中的严格模式,但我试图不这样做。请注意,我仍然是一个新手程序员,也许我什至误解了这行代码在幕后所做的事情。任何帮助表示赞赏。

【问题讨论】:

    标签: angular local-storage strict


    【解决方案1】:

    这是一个更好的解决方法:

    const user = JSON.parse(localStorage.getItem('user') || 'null')
    

    【讨论】:

      【解决方案2】:

      解析方法的参数类型为字符串,localStorage.getItem('user') 将返回字符串或null

      所以您的文本编辑器建议您使用逻辑或 (||) 来分配用户属性

      这意味着如果 JSON.parse(localStorage.getItem('user') return null 使用第二个字符串意味着'{}'

      所以你的用户属性值为空对象,空对象不为空;

      你可以这样做

      const localUser = localStorage('user');
      if(localUser) {
          const user = JSON.parse(localUser);
          return true;
      } else{
          return false;
      }
      

      【讨论】:

        【解决方案3】:

        如果找不到项目,Localstorage 将返回 null。 试试这个:

        get isLoggedIn(): boolean {
                const user = JSON.parse(localStorage.getItem('user') || null);
                return (user !== null) ? true : false;
            }
        

        【讨论】:

          猜你喜欢
          • 2018-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-28
          • 2012-04-05
          • 2019-12-25
          • 1970-01-01
          • 2018-09-09
          相关资源
          最近更新 更多