0

I have two open routes (eg: /home, /details). After user is logged in, I want to restrict the user to go to these pages, till he logout, by direct change in URL, or hitting back button.

I have used AuthGuard, for restricting users to go to protected routes,when he is not logged in.

canActivate(
 next: ActivatedRouteSnapshot,
 state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | 
 boolean {
  if (localStorage.getItem('isLoggedIn') === null || 
    localStorage.getItem('isLoggedIn') === 'false') {
    return true;
  }

  this.router.navigate([state.url]);
  return false;
})
alyson_216
  • 136
  • 14
  • create another `guard` that does the opposite of `AuthGuard` and use it on `/home` and `/details` – Iftifar Taz Jul 30 '19 at 16:19
  • Yes, I have done it. The code given is for another guard. Now I want to navigate back to previous state, if user wants to go to open routes without logout. Now using this.router.navigate([state.url]) does not gives me previous state always. Sometimes it gives / – alyson_216 Jul 30 '19 at 16:27
  • what you're after here is unclear, try to add more details – bryan60 Jul 30 '19 at 18:04

2 Answers2

0

You can create an array of home and details urls. For example,

const restrictedRoutes = ['about',  'details'];

And after checking user loggedIn or not, you can add one more condition of checking current routes exist in restrictedRoutes. Based on that you can redirect user to other pages.

if (restrictedRoutes.includes(route.url)) {
  // redirect path
}
this.router.navigate([state.url]);
  return false;
gaurav soni
  • 206
  • 1
  • 10
0

// general routes are '/home', '/details'

use a candeactivate authguard in other authenticated routes( where user should be loggedIn). there you can check the condition and reject/redirect.

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Router} from '@angular/router'; 

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  openRoutes = ['/home', '/details'];
  intendedRoute: string = '';
  constructor(private _router: Router) {
    this.intendedRoute = _router.url;
  }
  canDeactivate(component: CanComponentDeactivate) {
    return this.openRoutes .includes(this.intendedRoute)? component.canDeactivate() : true;
  }

}

if the condition is true you can cancel navigation by returning false from the canDeactivate method in your respective component.