sarasm
sarasm

Reputation: 345

Header component can be added in to every component HTML Angular 8

I am trying to implement role guard as per the below url http://coding-karma.com/2018/06/17/role-based-access-control-in-angular-4-route-guards-in-depth/

app.component.html has the following code

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

I have given the role checking in header like below

export class HeaderComponent implements OnInit {
constructor( private authService: authService,   private router: Router) {
    const token = localStorage.getItem('jwt');
    const tokenPayload = decode(token);
    console.log("tokenPayload.role", tokenPayload.role);
    this.Role = tokenPayload.role;
   }
 
   getRoleB(){
     if(this.Role=='FA' || this.Role=='FTH'){
       return true;
     }
     else{
      return false;
     }
   }
 
   getRoleC(){
    if(this.Role=='FA' || this.Role=='FTH' || this.Role=='FT'){
      return true;
    }
    else{
     return false;
    }
  }
}

Also after the successful login its going to the respective paths like below

const token = localStorage.getItem('token');
 
      // decode the token to get its payload
      const tokenPayload = decode(token);
      console.log(tokenPayload);
      if (tokenPayload['user_role'] == "user"){
        this.router.navigate(['/dashboard'])
            
      } else {
        this.router.navigate(['admin/dashboard'])
      }

I have only one problem. After successful login the router navigate to respective dashboards, but header it will show only common links. If i refresh the page everything works fine.

If i place the header in the dashboard it works fine. I would like to know is this the right approach ? adding the header in each component separately? Please suggest..

Upvotes: 0

Views: 1677

Answers (1)

Rahul Tokase
Rahul Tokase

Reputation: 1218

Ideally you should have app module which will render header,content and footer. and You should have dashbaord as a children to app module which will be loaded through route /dashboard. So dashboard should be your lazy loaded children module as shown below

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: './dashboards/dashboards.module#DashboardsModule'
  }
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

Upvotes: 1

Related Questions