如何在Angular中从浏览器的本地存储中同步获取数据 [英] How to fetch data from localstorage of a browser synchronously in Angular

查看:62
本文介绍了如何在Angular中从浏览器的本地存储中同步获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个非常简单的任务.我已经编写了代码,它也正在工作.但是有一个小问题.首先让我向您展示代码:

It seems to be a very simple task. I've written the code and it is working also. But there is a small issue. First let me show you the code:

navbar.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  currentUserFirstname="";
  currentUserLastname="";

  constructor() {
  }

  ngOnInit() {
    this.currentUserFirstname=localStorage.getItem('firstname');
    this.currentUserLastname=localStorage.getItem('lastname');
  }
}

navbar.component.html

<span class="current-user">{{currentUserFirstname}} {{currentUserLastname}}</span>

我只想显示要从存储中获取的当前登录用户.问题是,它永远不会第一次显示.看到,在绿色圆圈之后,什么也没有:

I just want to display the current logged in user which I've to fetch from storage. The problem is that, it is never displayed first time. See, after the green circle there's nothing:

但是当我刷新页面一次时.值出现.看:

But when I refresh the page once. The values appear. See:

我尝试使用 setTimeout(),但是没有用:

I tried using setTimeout() but it didn't work:

ngOnInit() {
    setTimeout(function(){
      this.currentUserFirstname=localStorage.getItem('firstname');
      this.currentUserLastname=localStorage.getItem('lastname');
   }, 2000);
  }

请帮助我.我需要帮助使此任务的代码同步.

Please help me. I need help making the code synchronous for this task.

推荐答案

本地存储即使在构造函数中也可以工作,因此请在函数尝试从存储中获取值之前,在其中检查或添加调试器,并检查本地存储是否包含该值.

Local storage works even in the constructors so please check or add debugger there and check if the local storage consists the value before the function tries to get it from the storage

这篇关于如何在Angular中从浏览器的本地存储中同步获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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