Storing a value in a variable from ngOnInit() in Angular 2

Upon logging into my app, I want to retrieve a JSON object stored in local storage and assign it to the user Object. The issue is that the first time I login, nothing is displayed. However, upon refreshing the page, I can see the first name of the user.

This is the .ts file:


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

When using it in the template, it should look like this:

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

How can this issue be resolved?

Answer №1

The variable needs to be set before your html can render properly

Include this snippet within your html code:

<span> {{ user?.last_name }} </span>

Utilizing the Safe Navigation Operator, you can avoid errors and display the last_name once it has a value assigned.

Answer №2

Through thorough research, I finally discovered the solution to my query on this platform.

An insightful discussion on loading data in Angular2 before component rendering

A special shoutout to @Wesley Coetzee for providing valuable assistance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate the toggle menu

Hi there! I'm currently working on a menu and I want the clicked item to become active, switching the active state to another item when clicked. However, my current implementation is not working as expected. Any assistance would be greatly appreciated ...

Guidance on displaying values from one PHP file in another PHP file

Is it possible to achieve this scenario? I have two files, named main.php and submenu.php. In main.php, I have the main menu defined as follows: In another file called submenu.php, I have a list structured like this: <ul> <li>1</li> &l ...

Tips for integrating new channels and categories using a Discord bot

Hey there! I'm trying to add channels and categories, but I can't seem to get the function ".createChannel" working. The console keeps telling me that the function doesn't exist. I've been referencing the documentation at https://discor ...

The organizational structure of data in MongoDB for posts, comments, saved content, and likes

I am currently diving into the world of MEANJS web development and working on structuring my data. As a newcomer to the NoSql concept, I am seeking guidance on the best practices to follow. The data I need to store includes: questions answers likes saved ...

What is the best way to retrieve a button's value upon clicking and display it in a React component?

Picture a calculator display. Each button press should output the value of that button once, and if pressed multiple times, the value should be displayed accordingly. import { useState } from "react"; function App() { const [data, setData] = ...

Having trouble updating the URL path with the $location service in Angular

I'm facing a challenge in updating the URL path using the $location.url service, as it's not reflecting the changes correctly. For instance, my current URL path is http://localhost:64621/module/commercial/#/company/98163780-4fa6-426f-8753-e05a6 ...

When attempting to duplicate a table row with JavaScript, the input fields fail to appear

Currently, I am facing an issue while working with a table and trying to copy a table row using JavaScript. The problem occurs when I click on the "Add More" button - the table row is copied, but the input fields are not displaying. Below is the code snipp ...

Employing jQuery to redirect to a different URL when a button is clicked

I've been experimenting with a project that involves both JQuery and AJAX. One of the features I have added is JQuery autofill. Here is the code snippet for the form: <form class="form-horizontal"> <div class="form-group"> < ...

Choose from the dropdown menu: click to select multiple options or deselect all by selecting a single option

Is there a way to create a Select box where all options can be selected with a single click and then unselected with another single click? The goal is to only allow the user to select one option at a time, rather than multiple options. <script src="h ...

Tips for executing a loop and fetching a URL in Angular 8

I've been attempting to fetch data from a URL and convert it into a JSON file for display using HTML. The URL of the JSON only differs by one digit, ranging from 1 to 10, "https://jsonplaceholder.typicode.com/todos/1" Despite my efforts to create a l ...

Leverage Javascript to detect the operating system and dynamically incorporate external HTML content

I am trying to identify the operating system of a user and then dynamically load HTML content from another file based on their OS. I have incorporated jQuery scripts from the previous version of the site in my attempts, but they are not entirely effective. ...

Leveraging redux within your NEXT.JS project

While working on my Next.js application, I have integrated Redux and Redux Saga. I am trying to incorporate server-side rendering for making HTTP requests: export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { store.dispatch(g ...

Exploring the contrast: resolve() versus fulfill() in q.js

I'm finding it difficult to understand the distinction between calling a resolver's resolve() as opposed to fulfill(). Both functions and terms "resolve a promise" and "fulfill a promise" are frequently used interchangeably. Can you provide guid ...

Vue.js component communication issue causing rendering problems

When it comes to the Parent component, I have this snippet of code: <todo-item v-for="(todo, index) in todos" :key="todo.id" :todo="todo" :index="index"> </todo-item> This piece simply loops through the todos array, retrieves each todo obj ...

Using jQuery to transform English into Latin numerals

I am looking to convert all English/Latin numbers in the body to Persian numbers. I have implemented the following code: $(document).ready(function () { persian = { 0: '۰', 1: '۱', 2: '۲', ...

Dealing with complications in the Rails asset pipeline management

I am working on a webpage that requires real-time data to be displayed. Therefore, it necessitates continuous ajax communication post page load. similar to this, jQuery -> setInterval -> $.ajax url: "some url" success: (data, te ...

Issue with changing color of intersectObjects in Three.js not being properly registered [example code in jsfiddle]

I'm encountering an issue where I can't seem to change the color of a cube when someone hovers over it. I've simplified the code as much as possible. Click here for the code <script> var container; var scene, camera, renderer, mouse, ...

verify selection on php page using javascript

I'm having trouble with confirming the deletion of something. Despite getting an alert message when clicking the 'deleteReply' button, nothing else appears to be happening. I've tried echoing the posted variable but it's not workin ...

The issue of the Ajax beforeSend function not triggering at times, causing a delay in displaying the bootstrap progress

I'm experiencing issues with my Bootstrap tabs and the progress bar not consistently showing up. I have 3 tabs, each displaying query results in a table. Whenever the search button is clicked or a tab is changed, an ajax call triggers a function with ...

Grid filtering challenges

I have implemented a filtering pipe logic for grid search. results.filter(item => Object.keys(item) .some(key => searchTerm.split(',').some(arg =>item[key]? item[key].toString().toLowerCase().includes(arg.toString().toLowerCas ...