Skip to content

Common use cases

AlexKhymenko edited this page Jan 26, 2018 · 15 revisions

Common use cases

Overview

  1. Two guards when first make request for authorisation and gets permissions second checks for permissions
  2. Save permissions on page refresh

Two guards when first make request for authorisation and gets permissions second checks for permissions

This method only works with angular 4.3.2 or higher see https://github.com/angular/angular/issues/15670

There are a lot of times you have 2 guard one for authorisation when it makes request for permissions and second is permissions guard and you want them to work in chain. To make them work in chain You should use them next

let routes = [
  { path: '', 
    canActivate: [AuthGuard],
    children: [
      {path: 'component', 
      component: ComponentName, 
      canActivate: [NgxPermissionsGuard],
      data: {
         permissions: {
           only: ['ADMIN', 'MODERATOR'],
           redirectTo: 'another-route'
         }
       }}
    ]
  }
]

Note: Make sure the permission request in chained in auth guard

   canActivate() {
       return authLogin().then((obj) => {
           // or load here if you dont need second request
           // this.permissions.service.loadPermissions(obj.permissions)
          
           return this.authPermissions.getPermissions('url');
       }).then((permissions) => {
           this.permissions.service.loadPermissions(permissions)
       )
   }

Save permissions on page refresh

When user refreshed the page all data is lost including permissions for that user. There are a lot of approaches saving user permissions depending on your business requirements. But most common is to save them to localStorage. And then load them from localStorage when an application starts.

login() { return authLogin().then((obj) => { // or load here if you dont need second request this.permissions.service.loadPermissions(obj.permissions); // Save permissions to localStorage. localStorage.setItem('permissions', JSON.stringify(obj.permissions)); }) }

Clone this wiki locally