You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中localStorage存储的内容无法在页面正常显示问题求助

问题修复方案
  • key大小写不匹配:localStorage的key是大小写敏感的,存储时用的key是isLoggedIn,取数据时写的是isloggedIn(首字母L小写),无法取到对应值。
  • 存储逻辑顺序错误:先执行了存储isLoggedIn的操作,之后才把this.isLoggedIn赋值为true,导致存储的永远是修改前的旧值(默认一般为false)。
  • 模板变量名不匹配:组件里把用户信息存在了user变量中,但模板里写的是item.username,不存在item变量自然无法渲染内容。
  • 默认值设置错误:isLoggedIn是布尔值,取不到值时给的默认值是'{}',JSON.parse后是空对象,渲染到页面会显示[object Object]而非预期的布尔值。
  • subscribe语法错误:原代码中subscribe的成功回调提前闭合了括号,error回调被放在subscribe参数外,属于语法错误,会直接导致代码运行报错。
修正后的代码

1. 登录存储逻辑修正

onSubmit() {
  this.submitted = true;
  if (!this.loginForm.valid) {
    return;
  }
  this.loading = true;
  this.authService.SignIn(this.f.login.value, this.f.password.value)
    .pipe(finalize(() => {
      if(this.loggedUser == null){
        this.router.navigate(['/Login']);
      }
      else{
        this.router.navigate(['/']);
      }
    }))
    // 修正subscribe括号位置,把error回调放在参数内
    .subscribe(
      response => {
        // 先修改变量值,再存储到localStorage
        this.loggedUser = response as User;
        this.isLoggedIn = true;
        localStorage.setItem('isLoggedIn',JSON.stringify(this.isLoggedIn)); 
        localStorage.setItem('loggedUser', JSON.stringify(response));        
        this.authService.setData(response as User);
        this.loading = false;
      },
      (error) => {
        this.error = error;
        this.loading = false;
        this.errorHandler.handleError(error);
        this.errorMessage = this.errorHandler.errorMessage;
      }
    )
}

2. 其他组件取数据逻辑修正

// key和存储时保持完全一致,布尔值默认值设为false
this.isLogged = JSON.parse(localStorage.getItem('isLoggedIn') || 'false');
// 用户信息取不到时默认设为null,避免空对象报错
this.user = JSON.parse(localStorage.getItem('loggedUser') || 'null');

3. 模板渲染逻辑修正

<!-- 变量名和组件内保持一致,加可选链避免user为null时抛出错误 -->
<p>IsLogged : {{isLogged}}</p>
<p>User : {{user?.username}}</p>

内容的提问来源于stack exchange,提问作者Paintbox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:30:01