...
/Implementing User Authentication Status in the Navbar
Implementing User Authentication Status in the Navbar
Learn to implement authentication status in Angular.
We'll cover the following...
In this lesson, we’ll implement the functionality that shows the authentication status of a user in the navbar. If the user is logged in to the application, the navbar will have the following items:
If the user is logged out of the application, the navbar status will show the nav item in the image below:
Implementing the logic for the navbar status
To set up the navbar logic in our application, we use the code below:
Press + to interact
import { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';import { Router } from '@angular/router';@Injectable({providedIn: 'root',})export class UserService {private baseURL = ' https://course-mgt-app.herokuapp.com';constructor(private http: HttpClient, private router: Router) {}registerUser(user: any) {return this.http.post(`${this.baseURL}/api/register`, user);}loginUser(user: any) {return this.http.post(`${this.baseURL}/api/login`, user);}get isLoggedIn(): boolean {const user = localStorage.getItem('token') as string;return user !== null ? true : false;}logoutUser() {localStorage.removeItem('token');this.router.navigate(['/home']);}}
Below is a summary of the code above:
-
We begin implementation from the ...