如何获取当前路线或(即将到来的路线)数据?

时间:2017-01-25 14:39:57

标签: angular angular2-routing

我的路线中有数据,我想把它放在后卫中。我尝试了一个使用ActivatedRouteSnapshot的教程,我得到了以下错误。

错误:没有ActivatedRouteSnapshot的提供者!

这是我的routes.ts:

import { LayoutComponent } from '../layout/layout.component';
import {LoginComponent} from './login/login.component';
import { AuthGuard } from '../core/auth/auth-guard.service';
export const routes = [

    {
        path: '',
        component: LayoutComponent,
        children: [
            { path: '', redirectTo: 'home', pathMatch: 'full', canActivate:[AuthGuard], data:{permission:'users.create'} },
            { path: 'home', loadChildren: './home/home.module#HomeModule',canActivate:[AuthGuard],data:{permission:'users.create'} }
        ]
    },
    {
        path: 'login',
        component: LoginComponent,
    },
    // Not found
    { path: '**', redirectTo: 'home' }

];

我的auth-guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router,ActivatedRoute } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private authService: AuthService, private router: Router, private route:ActivatedRoute) {}
    canActivate(){
        if(!this.authService.loggedIn()){
            this.router.navigate(['login']);
            return false;
        }else{
            if(this.route.data['permission']){
                if(!this.authService.hasAccess(this.route.data['permission'])){
                    return false;
                }
            }
        }
        return true;
    }
}

1 个答案:

答案 0 :(得分:2)

ActivatedStateSnapshotRouterStateSnapshot作为参数传递给CanActivate

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
   ...
}

https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html