0

In My Angular App I have setup the routing app.routing.ts as shown below:

const routes: Routes = [{
    path: '',
    redirectTo: '/login',
    pathMatch: 'full',
    canActivate: [LoginGuard]
},
{
    path: 'login',
    component: LoginComponent,
    canActivate: [LoginGuard]
},
{
    path: '',
    component: AdminLayoutComponent,
    canActivate: [AuthGuardService],
    data: {
        expectedRole: 'Admin'
    },
    children: [{
        path: '',
        loadChildren: './layouts/admin-layout/admin-layout.module#AdminLayoutModule'
    }]
},
{
    path: 'customer_dashboard',
    component: CustomerLayoutComponent,
    canActivate: [AuthGuardService],
    data: {
        expectedRole: 'Customer'
    },
    children: [{
        path: '',
        loadChildren: './layouts/customer-layout/customer-layout.module#CustomerLayoutModule'
    }]
},
{
    path: '',
    component: MobiLayoutComponent,
    canActivate: [AuthGuardService],
    data: {
        expectedRole: 'Mobilink'
    },
    children: [{
        path: '',
        loadChildren: './layouts/mobi-layout/mobi-layout.module#MobiLayoutModule'

    }]
},

{
    path: '**',
    redirectTo: 'login',
    pathMatch: 'full'
}
];

@NgModule({
imports: [
    CommonModule,
    BrowserModule,
    NgxUiLoaderModule.forRoot(ngxUiLoaderConfig),
    RouterModule.forRoot(routes),
],
exports: [],
})
export class AppRoutingModule {}

this is my login authenticate guard

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { LoginAuthenticateService } from './login-authenticate.service';
import * as decode from 'jwt-decode';

@Injectable()
export class LoginAuthenticateGuardService implements CanActivate {

constructor(public auth:LoginAuthenticateService,public router:Router) {
}

canActivate():boolean{
if (this.auth.isAuthenticated()) {
  const token = localStorage.getItem('token');
  const tokenPayload = decode(token);
  const user_role=tokenPayload['role'].toString();
  if(user_role=='Admin')
  {
   this.router.navigate(['dashboard']);
   return false;
  }
  else if(user_role=='Customer')
  {
    this.router.navigate(['customer_dashboard']);
    return false;
  }
  else if(user_role=='Mobilink')
  {
    this.router.navigate(['mobilink_dashboard']);
    return false;
  }
}
return true;

}

}

Everything was working fine except for one weird issue i.e when ever I hit the url localhost:4200 the browser routes me towards locahost:4200/login which is fine but whenever I manually refresh the page localhost:4200/login the Angular routes me towards localhot:4200/login/login which is weird and whenever I manually refresh the page localhost:4200/login/login I get nothing.

Benson OO
  • 477
  • 5
  • 22

0 Answers0