Tips for retrieving the current logged user's username using local storage in Angular Typescript

In my Angular application, users can log in with their email and password. I want to display the user's name in the dashboard menu as "Welcome James" when the current user is logged in. This information should be retrieved from localStorage and all user data is fetched from a MySQL database.

Code :

login.component.html :

<h1 style="text-align:center">
  <img src="../../assets/images/logo.png">
</h1>
<div class="login-wrap">
  <div class="login-html">

    <div class='login'>
      <div class='col-md-4 offset-4 mt-5' *ngIf='!this.isLogin'>
        <h2 class="login-header">S'identifier</h2>
        <form class="login-container" #myform="ngForm" (ngSubmit)="onSubmit(myform)">
          <div class='form-group'>
            <input class='form-control' type="email" name="email" placeholder="email" ngModel>
          </div>

          <div class='form-group'>
            <input class='form-control' type="password" name="password" placeholder="Password"
              [type]="hide ? 'password': 'text'" [(ngModel)]="passwordValue">
            <span class="material-icons" matSuffix (click)="hide = !hide">
              {{hide ? 'visibility': 'visibility_off'}}
            </span>
          </div>
          <input class='btn btn-outline-info' type="submit" value="Login">
        </form>
      </div>
      <div class='col-md-4 offset-4 mt-5' *ngIf='this.isLogin'>

        <h1>You are logged in</h1>
        <button class='btn btn-outline-info' (click)='logout()'>Log-out</button>

      </div>
    </div>
  </div>
</div>

login.component.ts :

export class LoginComponent implements OnInit {
  isLogin: boolean = false
  errorMessage: any
  hide =true;
  passwordValue='';

  constructor(
    private _api: ApiService, 
    private _auth: AuthService, 
    private _router:Router,  private toastr : ToastrService) { }

  ngOnInit(){
    this.isUserLogin(); 
  }
  
  onSubmit(form: NgForm) {
    
    console.log('Your form data : ', form.value);
    this._api.postTypeRequest('user/login', form.value).subscribe((res: any) => {
     
      switch (res.status) {
        case 0:
            this.toastr.error("you have a problem","Erreur");
            break;
        case 1:
            this._auth.setDataInLocalStorage('userData', JSON.stringify(res.data));  
            this._auth.setDataInLocalStorage('token', res.token);  
            this._router.navigate(['']);
            break;
        case 2:
            this.toastr.warning("your email or password is incorrect","Warning");
            this.passwordValue = '';
            break;
    }
    })
  }

  isUserLogin(){
    if(this._auth.getUserDetails() != null){
        this.isLogin = true;
    }
  }

  logout(){
    this._auth.clearStorage()
    this._router.navigate(['']);
  }
}

app.component.html (menu) :

<nav class="menu">
    <ol>
        <li class="menu-item"><a routerLink="adherents">Adherents</a></li>
        <li class="menu-item">
            <a routerLink="factures">Factures</a>
        </li>
        <li class="menu-item">
            <a routerLink="logs">Logs</a>
        </li>
        <li class="menu-item">
            <a routerLink="regions">Regions</a>
        </li>
        <li class="menu-item">
            <a routerLink="roles">Roles</a>
        </li>
        <li class="menu-item">
            <img class="img" src="../assets/images/user.png">
            <a>welcome james</a>
            <ol class="sub-menu">
                <li class="menu-item"><a routerLink="/login">LogOut</a></li>
            </ol>
        </li>
    </ol>
</nav>
<router-outlet></router-outlet>

auth-guard.service.ts :

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService {

  constructor( private _authService: AuthService,
    private _router: Router) { }

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      if (this._authService.getToken()) {
        return true;
      }
     
      this._router.navigate(['/login']);
      return false;
    }
    
}

auth.service.ts:

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor() { }


  getUserDetails() {
    if(localStorage.getItem('userData')){
      return localStorage.getItem('userData')
    }else{
      return null
    }
    
  }
  setDataInLocalStorage(variableName, data) {
      localStorage.setItem(variableName, data);
  }
  getToken() {
      return localStorage.getItem('token');
  }
  clearStorage() {
      localStorage.clear();
  }
  
  
}

Answer №1

In the app.component.ts file, you have the option to create a variable that retrieves user data and assign it to a variable called .userName

import { Component } from '@angular/core';

@Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.scss']
})
export class AppComponent {
    title = 'cgem';
    user:any;
    constructor(){}
    ngOnInit() {
        //It is important to attempt to retrieve the user data in the ngOnInit lifecycle hook.
        try{
           this.user= JSON.parse(localStorage.getItem("userData"));
        }catch(error){}    
    }

   //additional code can be added here
    
 }  

In your app.component.html file, you can display the user information by calling the user variable

...
<img class="img" src="../assets/images/user.png">
<a>Welcome {{user.name}}</a>
<ol class="sub-menu">
...

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

Hover over the full-width sticky navbar to reveal a dropdown menu that stays at

I am new to using Bootstrap techniques and I am attempting to combine two different styles in a navbar. One involves a sticky navbar and the other a full-width dropdown navbar, both found on an educational website. https://www.w3schools.com/howto/tryit.as ...

Pressing a sequence of buttons to meet a requirement using JavaScript

Currently, I have a set of four buttons that trigger an alert message when all of them are clicked. However, I am looking to modify this behavior so that the alert is displayed only when specific combinations of buttons are pressed, such as button1 and b ...

sass-loader in webpack ignoring tsconfig paths

It appears that the Sass-loader is not utilizing the path alias declared in the typescript configuration. When using @use or @import, it results in a "not found" error. Webpack resolve: { plugins: [new TsconfigPathsPlugin()], tsconfig "paths&quo ...

Material-UI: The Mystery of Missing CSS Properties

Struggling to apply a CSS class to an element from Material-UI: bw:hover { -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */ filter: grayscale(100%); } Tried using makeStyles: import { makeStyles } from '@material-ui/core/styles' ...

Displaying Previously Selected Value in HTML Dropdown Menu

Using a combination of PHP and HTML, I have created an HTML table that is generated using a PHP while loop. The dropdown menu on the page displays all distinct portfolio names from my MySQL database by executing the following code: $query2 = "SELECT DISTI ...

"Can you guide me on how to invoke a parent function from retryWhen in Angular

I'm struggling to figure out how to execute a function from retryWhen and then call the parent function once retryWhen is done. Any ideas on how I can achieve this? getStatuses(statusesType: string[]): Observable<IStatus[]> { let body ...

Is there a way to generate unique authentication numbers daily without the need to manually adjust any code

I am building a web application for commuters using vuejs and firebase. My goal is to implement the following feature: The employer provides the employee with a unique authentication code daily, which the employee (user) must enter when clicking the "go t ...

Explaining a database table by converting HTML code into MySQL

Greetings! I am currently working on a website that involves using MySQL, PHP, and HTML to manage data. However, I am facing an issue when trying to display the data from my database's table using PHP and SQL code. Here is the snippet of code I have w ...

What is the best way to align a button to the bottom right corner using CSS?

After successfully positioning the buttons to the bottom left, I encountered an issue where one of the buttons disappeared when navigating back to the page. The missing button only appears after scrolling down. Can someone please assist with this problem? ...

What is the reason behind the inability to overflow the Safari viewport?

My website, , has a footer that is clickable in Chrome but not in Safari. When users scroll to the footer in Safari, the screen jumps back to the top, making it inaccessible. Can anyone help me identify the issue? Below is the CSS code for my React projec ...

Calculate the total of the smallest values in three columns as they are updated in real-time

I'm facing an issue with dynamically adding the sum of the 3 lowest values entered in columns. The Total Cost Field is not displaying any value, and changing the type from number to text results in showing NaN. I've tried various approaches but h ...

A guide to programmatically downloading a file with JavaScript on Internet Explorer

I'm currently facing a challenge with my web page. There is a button that, when clicked, should generate a CSV file (by converting from JSON) for the user to download. I've implemented the logic based on this jsfiddle, and it works perfectly in C ...

What is the method for altering the appearance of grid columns with javascript?

What modifications do I need to make in JTML and Javascript? var opac; function checkfun() { opac=(Array.from(document.querySelectorAll('input[type="checkbox"]')) .filter((checkbox)=>checkbo ...

Copy the content of one input field into another field at the same time

I have encountered an issue that seems simple, yet the proposed solutions have not been effective. Most suggestions involve using jQuery, but Bootstrap 5 has shifted away from jQuery. I am looking for a solution using JavaScript or HTML only. The problem ...

"Strategies for aligning the div to the center of the entire page

Is there a way to vertically center content? I attempted using padding on top and setting vertical alignment, but it doesn't seem to work on mobile view. Can someone provide some guidance? <div style="padding-top:200px;vertical-align: middle;" ali ...

Deploying an Angular 6 application on GitHub Pages

I've been struggling to successfully deploy my application on Github Pages. I have a hosted repository that I used for testing purposes, and I followed all the necessary steps to get the application up and running, but unfortunately, everything I&apo ...

Two interdependent select fields

I am currently working on creating two select fields where, upon selecting an option in the first field, some options in the second field should be hidden. I have almost achieved this, but my script is unable to locate certain options in the first select f ...

Struggling with transferring a hidden form value from the database to a PHP if-statement

In my database table named "Related," I have 3 columns: related_id article_id object_id This table tracks the relationships between articles and objects. I recently updated the code to only include a delete button (x). When a user clicks on this button, ...

When attempting to access the property 'originalname' of an undefined nodejs Mongoose object, an error is triggered

I am attempting to save images using mongoose, express, and multer. However, I keep encountering the following error when testing with Postman: TypeError: Cannot read property 'originalname' of undefined var express=require("express") var ro ...

Strategies for Improving CSS Loading Speed

I have tried optimizing the CSS code for the following links, but I am still receiving an error message about optimized CSS delivery. http://fonts.googleapis.com/css?family=Droid+Sans%7CUbuntu+Condensed&ver=3.6 http://www.sampleurl.com/wp-content/th ...