Implementing User Authentication Status in the Navbar
Learn to implement authentication status in Angular.
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:
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
user.service.ts
file by importing the Angular router in line 3. -
Next, we inject the router as a private variable in the
constructor
in line 10. ...