简体   繁体   English

Angular 2 CanActivate不起作用

[英]Angular 2 CanActivate does not work

I'm trying to create route guard, read a few blogs and Angular 2 official documentation on it. 我正在尝试创建路线保护,阅读一些博客和Angular 2官方文档 But I still can't make it work. 但我仍然无法使其发挥作用。

Here's RouteGuard (I've removed logging logic to be sure that problem is in routing, not in authentication logic.): 这是RouteGuard(我已经删除了日志记录逻辑,以确保问题出在路由中,而不是在身份验证逻辑中。):

import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { Router, CanActivate, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class RouteGuard implements CanActivate {
  constructor() {
    var a = 5;
    console.log("RouterGuard called");
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    console.log("RouterGuard called");
    return true;
  }
}

Here i have some routes: 我在这里有一些路线:

import { RouteGuard } from './common/routeGuard';
import { ClassifiersComponent } from './components/classifiers/classifiers.component';
import { Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';

export const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'classifiers', component: ClassifiersComponent, canActivate: [RouteGuard] },
];

And then i pass them in bootstrapper method: 然后我在bootstrapper方法中传递它们:

import { RouteGuard } from './app/common/routeGuard';
import { ClassifiersComponent } from './app/components/classifiers/classifiers.component';
import { HomeComponent } from './app/components/home/home.component';
import { routes } from './app/app.routes';

@NgModule({
    imports: [
        RouterModule.forRoot(routes)
    ],
    providers: [
        { provide: LocationStrategy, useClass: PathLocationStrategy },
        { provide: APP_BASE_HREF, useValue: '/' },
        RouteGuard
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        ClassifiersComponent
    ],
    bootstrap: [AppComponent]
})
export class AppModule {}

I'm not sure what is wrong with this all, may be I'm missing something important. 我不确定这一切有什么问题,可能是我错过了一些重要的东西。 From debugging I can tell that it's hitting canActivate() breakpoint, but does not execute console.log, same goes for constructor. 从调试我可以看出它正在击中canActivate()断点,但不执行console.log,构造函数也是如此。

EDIT: Other routes where there is not any route authentication works fine. 编辑:没有任何路由验证的其他路由工作正常。

EDIT2: I'm using angular/core 2.2.0, angular/router 3.2.0 EDIT2:我使用的是角度/核心2.2.0,角度/路由器3.2.0

更新到角/核心2 3 2.0,角/路由器3.3 0.0解决了这个问题,我不知道为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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