Unable to access the correct item from local storage while a user is authenticated

I am facing an issue with retrieving the userid from local storage when a user is authenticated or logged in. The user id is not being fetched immediately upon logging in, and even when navigating from one page to another, it remains unavailable until I reload the page.

What could be causing this problem?

In my header component, I have a logo that includes a router link with the parameter userid. This router link only works when a user is logged in. If the user logs out, an ng if method is used to display a different logo instead of the logged-in one.

The issue arises when the user needs to manually reload the page for the userid to be fetched.

This is the code snippet from header.html:

<a class="navbar-brand" routerLink="" *ngIf="!this.authService.isAuthenticated()">
  <img src="assets/img/logo.png" alt="WAZ_logo">
</a>
<a class="navbar-brand" routerLink="/user-survey/{{Userid}}/{{name}}" *ngIf="this.authService.isAuthenticated()">
  <img src="assets/img/waz_home.png" alt="WAZ_logo">
</a>

And here is the code from header.ts:

ngOnInit() {
  debugger;
  this.Userid = localStorage.getItem('user_id');
  this.name = localStorage.getItem('user.name');
}

I am looking for a solution to retrieve the userid as soon as the user is logged in without requiring a manual page reload.

Answer №1

The localStorage is designed to store strings rather than objects. To save an object, you will first need to stringify it and then parse it when retrieving. Here's an example:

localStorage.setItem('user', JSON.stringify(user));
let user = JSON.parse(localStorage.getItem('user'));
console.log(user.name);

If you need to share data between the header component and the login component, consider using a service for communication.

https://stackblitz.com/edit/angular-qj6kof

https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

Answer №2

One suggestion is to create a login service that manages user authentication and information retrieval instead of relying on localStorage.

However, if you prefer to stick with localStorage, you can make the following adjustments in your code:

ngOnInit() {
  // leave this section empty
}

get Userid() {
   return localStorage.getItem('user_id');
}

get name() {
   return localStorage.getItem('user.name');
}

No changes are necessary for your header.html.

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

Issues with the alignment of ion-grid in Ionic/Angular application

I am facing an issue in my ionic/angular project where I am attempting to create two columns within a row using ion-grid, ion-row, and ion-col. However, the content of the second column is unexpectedly appearing below the first column instead of beside it. ...

Developing an asynchronous function to retrieve data from an external API utilizing Await/Async strategy

Currently, there is a method under development that retrieves a value from the API. What steps are needed to properly integrate Async/Await functionality into this process? fetchAccountById(){ let accountName; this.accountService.fetchDa ...

Different categories of properties within a generic function

I'm attempting to modify certain fields of my object using field names. Here is the code snippet I have written: interface Foo { a: number[], b: string[], } type Bar = { [T in keyof Foo] : (arg : Foo[T]) => Foo[T] } function test<T ex ...

Result from Nativescript ModalView

crongoramaModal() { let options = { context: {}, fullscreen: true, viewContainerRef: this.viewRef }; this.modalService.showModal(CronogramaManejoComponent, options) .then((result: CronogramaManejo)=>{ ...

Encountering issues with reassigning variables in Angular resulting in null or undefined values

Currently, I am dealing with a test array where the initial value is set to null. In my function, I am making some modifications to the test array. However, even though I am reassigning values to it, the console still shows it as a null or undefined array ...

A guide on utilizing Material UI Fade for smoothly fading in a component when a text field is selected

I am facing an issue with a text field input and a helper component. My goal is to have the helper component fade in when a user focuses on the input field. The helper component is wrapped as follows: <Fade in={checked}> <DynamicHelperText lev ...

Is there a feature similar to notifyWhenNoOutstandingRequests in Angular 2?

In my experience, test frameworks like Arquillian have utilized this method to determine when the DOM is ready for inspection with Angular 1. I am curious if there is a similar approach for accomplishing this in Angular 2? ...

Angular 6 triggers NavigationCancel event when encountering valid guards

I'm encountering difficulties with the Angular router while trying to navigate to a specific state. Despite my attempts to utilize a custom guard with canLoad() and canActivate() functions that return true, I have not been successful. The Angular do ...

Having trouble importing d3.js and typescript in IntelliJ?

Encountering errors in browsers' console when utilizing d3.select() in typescript code. Despite trying alternative methods like d3-timer.now(), the issue persists. As a newcomer to typescript, I am utilizing intelliJ Ultimate 2019.1. Through npm, I h ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...

"Encountering a 400 bad request error when making a Graphql POST

Seeking assistance with my graphql code. I have included the service and component files below. I am currently new to graphql and not utilizing the apollo client; instead, I am attaching a query on top of the HTTP POST call to send requests to the graphql ...

Improving Performance with Reusing Selectors in Ngxs

Working with Angular using the container/presentation pattern and Ngxs presents a challenge for me. The issue I am facing is that I have one container component nested within another container component, both calling the same @Select: @Select(State.example ...

One-stop shop for organizing import paths

Currently seeking a solution to streamline the management of import paths in Angular 2.0. Ideally, I would prefer to set up the configuration once and then simply reference it as needed, similar to using a variable. For instance: import { ProductService } ...

A more concise validation function for mandatory fields

When working on an HTML application with TypeScript, I encountered a situation where I needed to build an error message for a form that had several required fields. In my TypeScript file, I created a function called hasErrors() which checks each field and ...

Showing container element only if certain condition is met but display the children in Angular 2+

I am looking to create a grid-style view for a list of Angular components, where I can display up to 4 components in each row. The question that comes close to what I need is the following: Angular 2 NgIf, dont render container element on condition but sh ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

Oh no, an issue has occurred with The Angular Compiler! It appears that TypeScript version 3.9.10 was found instead of the required version, which should be >=3.6.4 and <

After upgrading my angular application from version 5 to version 9, I encountered an issue while trying to deploy my code on the server. ERROR in The Angular Compiler requires TypeScript >=3.6.4 and <3.9.0 but 3.9.10 was found instead. Even though ...

Utilizing Angular 2 Animations with the ngOnInit Lifecycle Hook

Suppose I envision a sleek navigation bar gracefully dropping down from the top of the browser once my app/website loads. Is it feasible to achieve this fluid motion using component animations metadata? Currently, I have managed to make it function as des ...

Is it possible to transform a webpack bundled javascript file into typescript source code?

Is it possible to decompile a webpack-bundled JavaScript file into TypeScript source code? I have a bundle.js file that was bundled using webpack, but the original source code files were accidentally deleted. I am hoping to reverse engineer the bundle.js ...

Error encountered: The import of 'createLocation' from 'history' failed. This issue occurred due to conflicting versions of History and React-Router-DOM

While attempting to configure an existing project on a new development server, I encountered the following error: ./node_modules/react-router-dom/esm/react-router-dom.js Attempted import error: 'createLocation' is not exported from 'histor ...