Skip to content
This repository has been archived by the owner on Dec 13, 2018. It is now read-only.

Add example showing how to enable/disable a link based on role #30

Open
mraible opened this issue Dec 14, 2016 · 1 comment
Open

Add example showing how to enable/disable a link based on role #30

mraible opened this issue Dec 14, 2016 · 1 comment

Comments

@mraible
Copy link
Contributor

mraible commented Dec 14, 2016

Router guards might be a good way to do this.

https://angular.io/docs/ts/latest/guide/router.html#!#guards

@jclancy93
Copy link

jclancy93 commented Dec 21, 2016

I have a rough solution to this using router guards if anyone has interest in seeing it.

//auth-guard.service.ts

import { Injectable }       from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
}                           from '@angular/router';
import { AuthService }      from './auth.service';
import { Account, Stormpath } from 'angular-stormpath';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router, public stormpath: Stormpath) {}


  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : any {
   return this.stormpath.user$
    .map(response => {
    	if(response == false) {
	    	console.log('no user found');
                this.router.navigate(['/login']);
    		return false;
    	}
    	else {
	    	console.log(response, 'user found')
    		return true;
    	}
    }).take(1);
  }

}

I import Stormpath which allows me to use this.stormpath.user$ which returns an observable<Account|Boolean>. CanActivate allows navigation to the route if returns true and 'guards' the route if returns false.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants