0

I want to implement a router guard based on the value in the store.if the user login to the application I want to get that user's role and activate the certain routes my submodule route.

I will post my current implementation but that didn't work at all

p.s I'm not using angular router store

canActivate(): {
   return this.store.pipe(select(selectUser)).pipe(
      skip(1),
      map((user) => {
        const userObj: any = user
        if (userObj.userRole === "Admin") {
          this.router.navigateByUrl('admin/tourprovider/genaral-infomation');
          return true;
        } else {
          this.router.navigateByUrl('home')
          return false;
        }

      })
     )
    }
NicoleZ
  • 1,485
  • 3
  • 22
  • 43

1 Answers1

1

I would try it like that:

private user$: Observable<any>;
constructor(
    private store: Store<{ user: string }>,
    private router: Router
  ) {
  this.user$ = store.pipe(select('user'));
}

canActivate(): {
  return this.user$.pipe(
    take(1),
    tap((user) => console.log(user)), // Just to test if user do have a value
    map((user: any) => (user.userRole  === "Admin") ? true : this.router.parseUrl('/home'))
  );
}

Norbert Bartko
  • 2,468
  • 1
  • 17
  • 36
  • this work but have a problem when a user role is an admin I want to be redirected to the admin portal triggering an infinite loop.what could be te problem – NicoleZ Sep 19 '19 at 08:51
  • When do you use this guard? Because a guard should be only used if you try to acces a a particular route and if you have access (are admin) he let you pass if not you'll get rediredted to the `/home` route. It should not redirect if you have access. – Norbert Bartko Sep 19 '19 at 09:10