最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2, How to store value in variable from ngOnInit()? - Stack Overflow

programmeradmin9浏览0评论

Here when I login to my app, i want to get json object stored in local Storage and then assign it to user Object. First time if I login it won't show anything but if I refresh the page I can see first name.

Here is .ts file

import { Component, OnInit } from '@angular/core';
@Component({
    selector: 'app-navbar',
    templateUrl: './navbarponent.html',
    styleUrls: ['./navbarponent.css']
})
export class NavbarComponent implements OnInit {
    user: Object;
    ngOnInit() {
    this.user = JSON.parse(localStorage.getItem('user'));
    }
}

And in template I want to use it like this:

<p> {{ user.first_name }} </p>

How can i solve this?

Here when I login to my app, i want to get json object stored in local Storage and then assign it to user Object. First time if I login it won't show anything but if I refresh the page I can see first name.

Here is .ts file

import { Component, OnInit } from '@angular/core';
@Component({
    selector: 'app-navbar',
    templateUrl: './navbar.ponent.html',
    styleUrls: ['./navbar.ponent.css']
})
export class NavbarComponent implements OnInit {
    user: Object;
    ngOnInit() {
    this.user = JSON.parse(localStorage.getItem('user'));
    }
}

And in template I want to use it like this:

<p> {{ user.first_name }} </p>

How can i solve this?

Share edited Aug 23, 2017 at 11:48 DreamTeK 34.3k29 gold badges124 silver badges178 bronze badges asked Aug 23, 2017 at 11:25 parthparth 6741 gold badge11 silver badges29 bronze badges 10
  • 1 @Vega no. That's a bad suggestion – Carsten Commented Aug 23, 2017 at 11:26
  • What's the problem with the current code? – Günter Zöchbauer Commented Aug 23, 2017 at 11:27
  • What is inside the user object? you can view it in the html by using {{user | json}} or just console.log it. – Carsten Commented Aug 23, 2017 at 11:27
  • Seems like you snippet is inplete. How are you injecting localStorage? Post some more relevant code – DAG Commented Aug 23, 2017 at 11:28
  • @dag sessionStorage and localStorage is globally available... – Carsten Commented Aug 23, 2017 at 11:28
 |  Show 5 more ments

2 Answers 2

Reset to default 7

Your html is rendering before the variable is being set

Inside your html use this:

<p> {{ user?.first_name }} </p>

This is called the Safe Navigation Operator which will prevent the error and render the first_name when it is populated.

After proper searching, found my answer here.

Angular2: How to load data before rendering the ponent?

@Wesley Coetzee, thanks for your support.

发布评论

评论列表(0)

  1. 暂无评论