Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

local storage - How to fetch data from localstorage of a browser synchronously in 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: enter image description here

But when I refresh the page once. The values appear. See: enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By the time your code gets executed, are you sure the values have been set to the localStorage yet?

It sounds like you would set them on any later event and of course if you refresh it had been set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...