Reputation: 145
I'm using Angular 2 with Router 3.0.0-aplha.8.
I'm trying to use CanActivate function to check if an user is authenticated. I have an AuthGuard that implements CanActivate, for now I only return true.
route.ts
import { Injectable } from '@angular/core'
import { provideRouter, RouterConfig, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import { AuthGuard } from './auth-guard'
import { SecurityComponent } from './security/security.component';
import { AdminDashboardComponent } from './admin/admin.dashboard.component';
export const mainRoutes: RouterConfig = [
{ path: '', component: SecurityComponent, },
{ path: 'admin', component: AdminDashboardComponent, terminal: true, canActivate: [AuthGuard] }]
export const MAIN_ROUTER_PROVIDER = provideRouter(mainRoutes);
auth-guard.ts
import { Injectable } from '@angular/core';
import {
CanActivate,
Router,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot){
return true;
}
}
When I try to access "/admin" (AdminDashboardComponent), I'm getting this error:
I have no idea what is happening. Someone has any idea?
Thanks Iván
Upvotes: 2
Views: 1442
Reputation: 1037
You need to bootstrap the guards too, so they can be used properly:
export const AUTH_PROVIDERS = [AuthGuard];
and then
export const MAIN_ROUTER_PROVIDER = [
provideRouter(mainRoutes),
AUTH_PROVIDERS,
];
more info here https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard
Upvotes: 2
Reputation: 4003
You need to bootstrap AuthGuard as well. Update your route provider as below
export const MAIN_ROUTER_PROVIDER = [provideRouter(mainRoutes), AuthGuard]
And adjust the bootstrap function to include this list bootstrap(appcomp,MAIN_ROUTER_PROVIDER)
Upvotes: 1
Reputation: 657058
I think if you change MAIN_ROUTER_PROVIDER
to
export const MAIN_ROUTER_PROVIDER = [provideRouter(mainRoutes), AuthGuard];
it should work.
Upvotes: 5