Jerome CAMUS Jerome CAMUS - 1 month ago 31
TypeScript Question

Angular 2.0.1 : router and canActivate class not working : No Directive annotation found on LoginGuard

here is my problem with latest Angular 2 (2.0.1) and angular router : 3.0.1

When I run application I have the following error :
Error: (SystemJS) No Directive annotation found on LoginGuard(…)

I have a router with a canActivate class to control access to route, here is the code :

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
export const MainWindowRoutes = [
{
path: '',
redirectTo: '/web-portal',
pathMatch: 'full'
},
{
path: 'web-portal',
component: MainWindowComponent,
children: [
{ path: 'device/:id', component: DeviceViewComponent, canActivate: [LoginGuard], pathMatch: 'full' },
{ path: 'location/:id', component: LocationViewComponent, canActivate: [LoginGuard], pathMatch: 'full' },
{ path: 'deviceType/:id', component: DeviceTypeViewComponent, canActivate: [LoginGuard], pathMatch: 'full' },
{ path: 'home', component: WelcomeViewComponent, canActivate: [LoginGuard], pathMatch: 'full' },
{ path: '', component: RouterComponent, canActivate: [LoginGuard], pathMatch: 'full' }
]
}
];
export const LoginRoutes = [
{ path: 'login', component: LoginComponent }
];
export const AUTH_ROUTER_PROVIDERS = [LoginGuard, LoginService];
export const appRoutes: Routes = [
...LoginRoutes,
...MainWindowRoutes
];

export const appRoutingProviders: any[] = [

];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);


Here is the loginGuard class :

import { Injectable } from '@angular/core';
import {
CanActivate,
Router,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';
import { LoginService } from './login.service';
import { routing } from '../app.routes';

@Injectable()
export class LoginGuard implements CanActivate {


constructor(private loginService: LoginService, private router: Router) { }

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

console.log('canActivate !!!');

if (this.loginService.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}


In app.module I boostrap the router like this :

bootstrap: (AppComponent, [AUTH_ROUTER_PROVIDERS ])


But it's not working at all. Injection seems not working correctly for canActivate class (LoginGuard).

Please help! ;-)

Regards

Answer

The bootstrap line in is invalid. It should be something like:

@NgModule({
  imports: [BrowserModule, ModuleWithProviders],
  providers: [AUTH_ROUTER_PROVIDERS],
  bootstrap: [AppComponent],
  ...
}
export class AppModule {}
// The browser platform with a compiler
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

// The app module
import { AppModule } from './app.module';

// Compile and launch the module
platformBrowserDynamic().bootstrapModule(AppModule);

See also

Comments