1

I am making angular application, where i am using routing and auth guard..

stackblitz

app component html

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <ul class="nav nav-tabs">
        <li role="presentation" routerLinkActive="active"
        [routerLinkActiveOptions]="{exact:true}"><a routerLink="/">Home</a></li>
        <li role="presentation" routerLinkActive="active"><a routerLink="/servers">Servers</a></li>
        <div *ngIf="showUser">
        <li role="presentation" routerLinkActive="active"><a routerLink="/users">Users</a></li>
        </div>
      </ul>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <router-outlet></router-outlet>
    </div>
  </div>

In the above code that i have made a if condition,

        <div *ngIf="showUser">
        <li role="presentation" routerLinkActive="active"><a routerLink="/users">Users</a></li>
        </div>

Show if showUser is false, then he cannot view the user tab in the home page..

TS:

export class AppComponent{
  showUser : boolean = true;

  ngOnInit() {
    this.showUser = false;
  }
}

Here i have hard coded this.showUser as false, whereas in real application , it will be based on some condition like,

  ngOnInit() {
    let user = this.localStorage.getItem('user');
    if(user.value == null || user.value == undefined) {
       this.showUser = false;
     }
  }

So the condition is false and hence the user menu not showing in view..

But if i change the url like

https://routing-angular-bjbjqd.stackblitz.io/users

See carefully i have added users at the last.. The above is redirecting to users page..

My requirement is it should not happen.

Because unless the condition is true it should not get redirected to users page.

How to prevent the url change unless showUser is true?

James Z
  • 12,209
  • 10
  • 24
  • 44
Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116

2 Answers2

1

You must control this perform from UserGuard.

First, set showUser variable as global variable trought localStorage

localStorage.setItem('showUser', true|false);

Second, get localStorage in the guard and review each try to access the path

@Injectable()
class UserGuard implements CanActivate {
  constructor() {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
    return localStorage.getItem('showUser');
  }
}

I hope it helps

0

Auth guard is not enough to complete your requirement. You need to use admin guards or User Specific guard to implement this.

import { Injectable } from '@angular/core';
import {
    CanActivate, Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot,
    CanActivateChild,
    NavigationExtras,
    CanLoad, Route
} from '@angular/router';

@Injectable()
export class UserGuard implements CanActivate, CanActivateChild, CanLoad {
    userType: string;
    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url;
        return this.checkLogin(url);
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.canActivate(route, state);
    }

    canLoad(route: Route): boolean {
        let url = `/${route.path}`;
        return this.checkLogin(url);
    }

    checkLogin(url: string): boolean {
        this.userType = sessionStorage.getItem('userType'); // check usertype here
        if (this.userType === "user") {
            return true;
        }
    }
}

Define routing like this:

{ path: 'user', component: UserComponent, canActivate: [AuthGuard, UserGuard] }