Ad

How To Redirect User According To Their Type, When Login?

- 1 answer

I am developing a school transport application with Ionic 4 and Firebase. Firebase has the authentication functionality, and there is a register of different users in the application (such as driver, student, company / adm), with the use of ID references (where the id generated by the authentication is referenced according to the user) . With that, I got into a problem that I'm breaking my head. How do I redirect each type of user to a respective page, according to their functionality, after logging in?

Ad

Answer

You can redirect using guard and local Storage

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {
  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      const token = localStorage.getItem('token');
      const role = localStorage.getItem('id');

    if (role === 'driver' && !!token) {
      this.router.navigate(['/driver']);
      return true
    } else if (role === 'student' && !!token) {
      this.router.navigate(['/student']);
      return true
    } else if (role === 'student' && !!token) {
      this.router.navigate(['/student']);
      return true
    } else if (role === 'admin' && !!token) {
      this.router.navigate(['/admin']);
      return true
    } else {
      this.router.navigate(['/login']);
      return false
    }
    return false
  }
}

Ad
source: stackoverflow.com
Ad