无法获取 CanActivate 防护中惰性模块的路由参数

Thi*_*ier 4 angular2-routing angular

我有一个以这种方式使用惰性模块的应用程序:

export const routes: Routes = [
  {
    path: '',
    component: WelcomeComponent
  },
  {
    path: 'items',
    loadChildren: 'app/modules/items/items.module#ItemsModule'
  }
];

export const AppRoutingModule: ModuleWithProviders
                      = RouterModule.forRoot(routes);
Run Code Online (Sandbox Code Playgroud)

在 中ItemsModule,我想对其中一条子路线使用守卫:

const routes: Routes = [
  {
    path: ':slug', component: ItemComponent,
    canActivate: [ ItemFetchGuard ]
  }
];

export const coveragesRoutingModule: ModuleWithProviders = 
                          RouterModule.forChild(routes);
Run Code Online (Sandbox Code Playgroud)

这个守卫需要获取slug参数来获取数据:

@Injectable()
export class CoverageFetchGuard implements CanActivate {
  constructor(
    private service: ItemService,
    private route: ActivatedRouteSnapshot,
    private ngRedux: NgRedux<IAppState>) {}

  canActivate() {
    const slug = this.route.params['slug'];
    return this.service.getItem(slug)
      .map(item => {
        this.ngRedux.dispatch(itemSuccessfullyFetched(item));
        return true;
      })
      .catch(error => {
        this.ngRedux.dispatch(itemFetchFailed(error));
        return Observable.of(false);
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

slug问题是我在路由快照中找不到该参数(即使在其children属性中)。看来这个数据稍后可以获得,但我找不到方法来获取它......

实现这一点的方法是什么?感谢您的帮助!

Thi*_*ier 5

我终于发现了“问题”(实际上不是问题)。我没有以正确的方式使用守卫。我们需要利用该方法的参数来使用有关当前路由的提示,canActivate而不是尝试从依赖注入中获取它们。

获取参数的方法如下:

@Injectable()
export class ItemFetchGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot,
              state: RouterStateSnapshot) {
    const slug = this.snapshot.params['slug'];
    (...)
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是相应的plunkr:http://plnkr.co/edit/UVz5YUkK0JoAy0i64Lo3 ?p=preview