2

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:

enter image description here

I have no idea what is happening. Someone has any idea?

Thanks Iván

IvanMoreno
  • 145
  • 10

3 Answers3

5

I think if you change MAIN_ROUTER_PROVIDER to

export const MAIN_ROUTER_PROVIDER = [provideRouter(mainRoutes), AuthGuard];

it should work.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Ed Morales
  • 1,027
  • 5
  • 9
1

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)

Arpit Agarwal
  • 3,993
  • 24
  • 30