Obtaining user data in Angular post login

My goal is to retrieve user data and display it anywhere on my website. For example, I want to fetch the user's name and show it on the homepage once they are logged in.

Any suggestions? Thank you

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. While I am able to extract user data from the token, I am facing challenges in mapping it to the user interface.

Answer №1

In order to access user information, it is necessary to subscribe to the API or utilize the user login function. Additionally, the local storage key value pairing is not being utilized correctly in this instance. Check the user login function for more details as it pertains to setting the Token(Users[0].

Answer №2

Once the data is accessible within the token that has been received, you have the ability to extract it post login and fetch it utilizing a getter method which will return the user if they are authenticated, or null if not (or opt for promises for a more organized approach).

The getter method retrieves the information stored in the session storage's token (if available) and presents it in a user-friendly format. This makes it convenient to access user data from any component - simply import the service in the constructor and invoke the getter to retrieve the necessary details.

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

Display the number of likes without having to refresh the page

On my website, there is a like/unlike post feature. When I click the like button, I want the value of check2 to appear next to the like button without needing to refresh the page. Currently, after clicking like, the data is inserted but only appears after ...

Uncaught ReferenceError: ajaxUrl is undefined

After pressing a green button on the website , instead of the expected popup image and email confirmation, I receive an error message stating "ajaxUrl is not defined". I have attempted to find a solution to this problem by searching on Google and Stackove ...

Changing images dynamically in tinymce using JavaScript

When using the tinymce editor, I attempt to modify my images. I currently have an image within it and I am trying to dynamically change the path of this image with: tinymce.activeEditor.selection.getNode().src = '/my/path/' Surprisingly, this m ...

The xModal window will only pop up once, after which a page refresh is required

My modal window opens when a user clicks on a div, but I'm having an issue. The modal window doesn't reopen when I click on the div again. Here is my code: <div onclick="document.getElementById('id01').style.display='block&apos ...

Refreshing user information on Ionic platform

Hello there, I am seeking assistance on updating user data in Angular and Ionic. I have managed to retrieve the user ID from local storage and create a method to store the new user data. However, I'm struggling with updating the user with this new inf ...

Zod offers the flexibility to customize validation for optional keys

Currently, I am exploring the utility of using zod within my application. I am facing a minor issue when attempting to parse an object that may contain optional keys. While using .passthrough allows the keys to remain in the object, I am interested in cu ...

What is the best method in ASP.NET Boilerplate for retrieving JSON data?

I have been facing an issue while working on this code, constantly running into the error message: Unexpected token o in JSON at position 1 https://i.stack.imgur.com/43Ewu.png I am struggling to troubleshoot and was hoping for some advice or tips on r ...

Submitting Data in Ionic 3 using Http Post and Storing in Sqlite with Angular 4

I am facing an issue while trying to post an array of contacts on a WebService. When I send the array, the data appears as NULL in the WebService response. I am confused about how to use Let params{} The error message shows "object undefined". Addition ...

Modifying the default text within a select box using jQuery

Within a select box identified as 'edit-field-service-line-tid', there is default text displayed as '-Any-'. This particular select field has been generated by Drupal. I am looking to use jQuery to change the text '-Any-' to ...

Question inquired regarding a specific line of code in Javascript/Angular

While working in a factory, I am tasked with constructing an HTML page that includes a form. To successfully manipulate the form, I need to access the FormController. After conducting some research online, I managed to achieve my goal using the following l ...

The FontLoader feature seems to be causing issues when integrated with Vuejs

While working on a Vue project with threejs, I encountered an error similar to the one described here. The issue arose when attempting to generate a text geometry despite confirming that the path to the typeface font is accurate and in json format. ...

I keep encountering an issue with getJson

A snippet of my JavaScript code retrieves a JSON object from a URL. Here is the portion of the code in question: <script> $(document).ready(function(){ $("button").click(function(){ $.getJSON('url_address', {}, function(data) { ...

Using MobX to alter observed observable values outside of actions is not permitted in combination with Ant Design components

When trying to upload files to the server and receive a response, I encountered an issue. If I override the onChange property of the Upload component (from antd), mobx starts throwing errors and the file uploading process gets stuck in the 'uploading& ...

What is the proper way to utilize a custom property that has been incorporated into my Pinia stores in a Typescript project?

Currently utilizing Vue 3 alongside Pinia; my api service is utilized for making requests to the api. I have included it as a property to ensure availability across all stores: In my main.ts file: import { http } from "@/services/http"; const s ...

Error: NgbAlert from ng-bootstrap cannot resolve all parameters when used with angular2-meteor

I am currently working on a meteor project that utilizes Angular as its front end. I am facing some challenges in importing @ng-bootstrap/ng-bootstrap into my project correctly. Here are the details of my setup... Meteor Version: 1.6, Angular Version: 5.1 ...

HTML TABS: Make the first TAB automatically selected

I've been experimenting with tabbing in HTML using a tutorial I found on W3SCHOOLS. While the source code provided works fine, I'm encountering an issue with automatically selecting the first tab by default. The tutorial doesn't cover this, ...

The functionality of React useState seems to be operational for one state, but not for the other

I am currently working on developing a wordle-style game using react. Within my main component, I have implemented a useEffect that executes once to handle initialization tasks and set up a "keydown" event listener. useEffect(() => { //The getWor ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Error message: Unspecified service injected

I am currently working with 2 separate javascript files for my project. One is being used as a controller, while the other serves as a service. However, when I attempt to inject the service into the controller and access its function, an error message pops ...

Navigating through a multidimensional array in Angular 2 / TypeScript, moving both upwards and downwards

[ {id: 1, name: "test 1", children: [ {id: 2, name: "test 1-sub", children: []} ] }] Imagine a scenario where you have a JSON array structured like the example above, with each element potenti ...