简体   繁体   中英

NoProviderError using CanActivate in Angular 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:

在此输入图像描述

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

Thanks Iván

I think if you change MAIN_ROUTER_PROVIDER to

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

it should work.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM