Search code examples
angularangular-ui-router

How to Determine a Route With Path Value


Please, I am having some kinda challenge solving this scenario. Whenever my app starts, it goes to a DummyComponent which has no url path value (http://localhost:4200/). This have just have two buttons, login and register. Pending on whichever button you click on; it navigates to the page.

Lets assume a user clicks on the login button to auth into the system, once successful, the user is redirected to the dashboard component => http://localhost:4200/dashboard.

Now, even when the user is logged in and manually change the url to http://localhost:/4200. This has no path value, how do I redirect the user back to http://localhost:4200/dashboard

I understand I can use the canActivate guard to protect my route, but the challenge I am having is; how can I determine when a user visit a url without a path value i.e http://localhost:4200/ (when logged in) so that I can redirect the user back to dashboard? …. But again, when the user is not logged in and visit the url without a path, it should go straight to the initial DummyComponent.

Here is how my route looks like:

const routes4: Routes = [
   {path: '', component: DummyComponent},
   {
     path: '',
     runGuardsAndResolvers: 'always',
     canActivate: [AuthGuard],
     children: [
      { path: 'dashboard', component: DashboardComponent },
       { path: 'user/list', component: PatientsComponent },
       { path: 'user/new', component: PatientComponent },
       { path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
     ]
   },
];
****
canActivate(): boolean {
      if (this.authService.isLoggedIn()) {
        return true;
      }
      this.pnotifyService.error('Error', 'You do not have sufficient permission');
      this.router.navigate(['/login']);
      return false;
  }

I did some research but couldn’t lay my hands on a scenario like mine.

Any idea on how to tackle this?


Solution

  • You can use another gaurd to redirect the user to proper path based on your condition

    Something like this:

    import { Injectable }     from '@angular/core';
    import { CanActivate }    from '@angular/router';
    import { Router } from '@angular/router';
    
    @Injectable()
    export class RedirectGuard implements CanActivate {
      canActivate() {
    
        if (this.authService.isLoggedIn()) {
             // when user is logged in you redirect it to dashboard url
             this.router.navigate(['dashboard']);
             return true;
        }
      }
     //Constructor 
     constructor(private router: Router, private authService: AuthService) { }
    }
    

    Now you can use it in your path like this:

    const routes4: Routes = [
       {path: '', component: DummyComponent},
       {
         path: '',
         runGuardsAndResolvers: 'always',
         canActivate: [AuthGuard, RedirectGuard],
         children: [
          { path: 'dashboard', component: DashboardComponent },
           { path: 'user/list', component: PatientsComponent },
           { path: 'user/new', component: PatientComponent },
           { path: '**', redirectTo: 'dashboard', pathMatch: 'full'}
         ]
       },
    ];
    

    Update:

    You can re-use your existing code to achieve this behavior

    Something like this:

    canActivate(): boolean {
          if (this.authService.isLoggedIn()) {
            this.router.navigate['/dashboard'] //redirect if the user is logged in
            return true;
          }
          this.pnotifyService.error('Error', 'You do not have sufficient permission');
          this.router.navigate(['/login']);
          return false;
      }