本文介绍了在Angular 2中使用CanActivate的NoProviderError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Angular 2与Router 3.0.0-aplha.8一起使用.

I'm using Angular 2 with Router 3.0.0-aplha.8.

我正在尝试使用CanActivate函数检查用户是否已通过身份验证.我有一个实现CanActivate的AuthGuard,现在我只返回true.

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;
   }
}

当我尝试访问"/admin"(AdminDashboardComponent)时,出现此错误:

When I try to access "/admin" (AdminDashboardComponent), I'm getting this error:

我不知道发生了什么.有人有主意吗?

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

谢谢伊万

推荐答案

我认为如果您将MAIN_ROUTER_PROVIDER更改为

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

应该可以.

这篇关于在Angular 2中使用CanActivate的NoProviderError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:20