Home > Blockchain >  How to get user data in Angular after login
How to get user data in Angular after login

Time:12-06

What I want to do is to get the user data and output it anywhere on my website. For example I would like to get the name for the user and output it on the homepage when the user is logged in.

any ideas ? Thanks

AuthService

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { EnvironmentUrlService } from './environment-url.service';
import { UserRegistrationDto } from '../models/user/UserRegistrationDto.model';
import { RegistrationResponseDto } from '../models/user/response/RegistrationResponseDto.model';
import { UserAuthenticationDto } from '../models/user/UserAuthenticationDto.model';
import { AuthResponseDto, user } from '../models/user/response/AuthResponseDto.model';
import { Subject, BehaviorSubject, Observable, map } from 'rxjs';
import { JwtHelperService } from '@auth0/angular-jwt';


@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  private authChangeSub = new Subject<boolean>()
  public authChanged = this.authChangeSub.asObservable();

  constructor(private http: HttpClient, private envUrl: EnvironmentUrlService, private jwtHelper: JwtHelperService) {}

  public registerUser = (route: string, body: UserRegistrationDto) => {
    return this.http.post<RegistrationResponseDto> (this.createCompleteRoute(route, this.envUrl.urlAddress), body);
  }

  public loginUser = (route: string, body: UserAuthenticationDto) => {
    return this.http.post<AuthResponseDto>(this.createCompleteRoute(route, this.envUrl.urlAddress), body);
  }

  public sendAuthStateChangeNotification = (isAuthenticated: boolean) => {
    this.authChangeSub.next(isAuthenticated);
  }

  public logout = () => {
    sessionStorage.removeItem("token");
    this.sendAuthStateChangeNotification(false);
  }

  public isUserAuthenticated = (): boolean  => {
    const token = sessionStorage.getItem("token");
 
    return token && !this.jwtHelper.isTokenExpired(token);
  }

  private createCompleteRoute = (route: string, envAddress: string) => {
    return `${envAddress}/${route}`;
  }
}

login.component.ts

  loginUser = (loginFormValue: any) => {
        this.showError = false;
        const formValues = {... loginFormValue };
    
        const userForAuth: UserAuthenticationDto = {
          email: formValues.email,
          password: formValues.password
        }
    
        this.authService.loginUser('api/accounts/login', userForAuth)
        .subscribe({
          next: (res:AuthResponseDto) => {
           sessionStorage.setItem("token", res.token);
           this.authService.sendAuthStateChangeNotification(res.isAuthSuccessful);
           this.notificationService.showNotification('success','Login successfully')
           this.router.navigate([this.returnUrl]);
        },
        error: (err: HttpErrorResponse) => {
          this.errorMessage = err.message;
          this.showError = true;
        }})
    }

**AuthResponse & User **

export interface AuthResponseDto {
    isAuthSuccessful: boolean;
    errorMessage: string;
    token: string;
}


export interface user {
     userId: string;
     userName: string
     firstName: string;
     lastName: string;
     role: string []
}

`

I can successfully register and log in a user. I can get the user data from the token but can't map it to user interface

CodePudding user response:

You have to subscribe the api or function user login to get the user information. Also the local storage key value pairing is not used properly here. check user login function, it shows this. set Token(Users[0].

CodePudding user response:

If the data is available in the token received, you can extract it after login and retrieve it with a getter method that return user if user is authenticated, null otherwise (or using promises, that would be cleaner).

The getter method retrieves the data stored in the token of the sessionStorage (if exists) and returns it formatted as user interface. Then you can access the user data fron any component, just import the service in the constructor and call the getter to get the data.

  • Related