While your system grows and grows, it’s almost certain it will eventually reach a state where some sort of permission or role management is needed. This can be modeled in many different ways, having different default user roles that have different purposes, or even more granular approaches, where each feature has different access levels and every user has individual permissions in your system.

While every case is a unique case, the same concept can be applied to every one of them in Angular since they have the same purpose of restraining specific parts of your system.

Guards, Services, and Directives

To control what a user can or cannot see, we need to restrict entire pages or remove certain parts of a page for this specific user. To limit user access to a page, we can use CanActivate guards, which is basically a class with a CanActivate method which will determine if a user should or should not see a specific page. This is calculated before showing the page and can be used with redirects too.

@Injectable()
export class DashboardGuard implements CanActivate {

  constructor(protected cookieService: CookieService,
              protected router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree {
    if (this.cookieService.check('user')) {
      return true;
    }
    return this.router.parseUrl('login');
  }
}

#typescript #angular #rxjs #javascript #programming

Dealing With Permissions in Angular and NgRx
4.75 GEEK