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:
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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…