Search code examples
angularsession-stateangular-servicesangular-components

Display Login Name and Role on Every Page Angular 2


I am newer to angular 2; I have an application and I want to display the currently logged in username and assigned role in my header component on every page within my application. I have:

  • user-model (the user interface with necessary fields for display such as username, role, and the person's name)
  • user-service (the service class to call the REST end point to get the data from our authentication system

I can easily get the user info from the log in, it comes across as valid JSON, but how do I display it on every page (components) WITHOUT having to call my service on every single component? Ideally, after the login page the header or starting component will load the user object and inject or pass that to all subsequent components, so the user object is stored (for lack of a better word) from component to component so only 1 http call is needed on application load.

Essentially I am looking for the best, most stream lined approach to this. It seems like a common scenario, but most people I read who write answers related to this say to call the service in every component. That would mean an API end point call is initiated on every page load? Can we store this data in session or cookie?

Thanks!


Solution

  • You can build a service that holds on to your user. I have an example here: https://github.com/DeborahK/Angular-Routing

    Here is one piece of it:

    import { Injectable } from '@angular/core';
    
    import { IUser } from './user';
    import { MessageService } from '../messages/message.service';
    
    @Injectable()
    export class AuthService {
        currentUser: IUser;
        redirectUrl: string;
    
        constructor(private messageService: MessageService) { }
    
        isLoggedIn(): boolean {
            return !!this.currentUser;
        }
    
        login(userName: string, password: string): void {
            if (!userName || !password) {
                this.messageService.addMessage('Please enter your userName and password');
                return;
            }
            if (userName === 'admin') {
                this.currentUser = {
                    id: 1,
                    userName: userName,
                    isAdmin: true
                };
                this.messageService.addMessage('Admin login');
                return;
            }
            this.currentUser = {
                id: 2,
                userName: userName,
                isAdmin: false
            };
            this.messageService.addMessage(`User: ${this.currentUser.userName} logged in`);
        }
    
        logout(): void {
            this.currentUser = null;
        }
    }
    

    The key part for you is the "currentUser" property.

    NOTE: This is a sample app so the user info is hard-coded. You'd need to retrieve the actual data.

    UPDATE: When accessing the currentUser from a component, be sure to use a getter. That will ensure you always get the current value if it is changed. I access the current user's name in my MenuComponent, so the code looks like this:

      get userName(): string {
        return this.authService.currentUser.userName;
      }
    

    If you want the entire user instance, use something like this:

      get user(): IUser {
        return this.authService.currentUser;
      }