angular - 无法获取 CanActivate 守卫中惰性模块的路由参数

标签 angular angular2-routing

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

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

export const AppRoutingModule: ModuleWithProviders
                      = RouterModule.forRoot(routes);

ItemsModule 中,我想为其中一个子路由使用守卫:

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

export const coveragesRoutingModule: ModuleWithProviders = 
                          RouterModule.forChild(routes);

这个守卫需要获取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);
      });
  }
}

问题是我无法在路由快照中找到 slug 参数(即使在其 children 属性中)。好像这个数据以后可以用但是我找不到办法获取它...

实现它的方法是什么?感谢您的帮助!

最佳答案

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

获取参数的方法如下:

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

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

关于angular - 无法获取 CanActivate 守卫中惰性模块的路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125823/

相关文章:

Angular 2 : assets not loaded when deployed in subdirectory

Angular 2 新路由器 : Change/Set Query Params

子路由中的 Angular 2 路由参数

dart - Angular2:导航到路由并弹出回到pushState堆栈的根

angular - 无法绑定(bind)到 'routerLink',因为它不是 'a' 的已知属性。尽管引用了路由器模块,但还是有错误

angular - 如何在 angular4 中读取 APP_INITIALIZER 服务中的查询参数?

angular - 如何使用Angular 2自动执行 Electron 应用程序的工作流程

angular - 如何使用 indexedDB 的 promise 在@ngrx/core 中设置initialState

css - ionic : Sticky button at the bottom of a particular ion-slide

angular - 链接 HTTP promise 时如何调用 catch 方法?