Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何解析Angular 2中的route param_Angular_Angular2 Router - Fatal编程技术网

如何解析Angular 2中的route param

如何解析Angular 2中的route param,angular,angular2-router,Angular,Angular2 Router,我有路线配置 const appRoutes: Routes = [ { path: '', loadChildren: 'app/+home/home.module#HomeModule' }, { path: 'auth', loadChildren: 'app/+auth/auth.module#AuthModule' }, { path: ':category', loadChildren: 'app/+search/search.module#SearchModule' }

我有路线配置

const appRoutes: Routes = [
  { path: '', loadChildren: 'app/+home/home.module#HomeModule' },
  { path: 'auth', loadChildren: 'app/+auth/auth.module#AuthModule' },
  { path: ':category', loadChildren: 'app/+search/search.module#SearchModule' },
  {
    path: '**',
    component: PageNotFoundComponent,
    data: { title: 'Page not found' }
  },
];
我需要检查:category route param值是否作为搜索类别存在于数据库中,如果是,请激活route,否则转到404页,在本例中为PageNotFoundComponent

使用CanActivate是最好的方法吗?导航到404页怎么样?

是的,您可以使用CanActivate guard

{ 路径:':类别', loadChildren:'app/+search/search.moduleSearchModule' canActivate:[CanActivateCategory] }, 然后,在防护装置内部执行重定向:

@注射的 类CanActivateCategory实现CanActivate{ 构造器专用路由器:路由器, 私有categoryService:categoryService{} 激活 路由:ActivatedRouteSnapshot, 状态:RouterStateSnapshot :可观察的|承诺|布尔值{ const obs=this.categoryService.categoryExistsroute.params['category']; obs.subscribeexists:boolean=>{ 如果!存在此.router.navigate'/404'; }; 返回obs; } } 此代码假设您有一个CategoryService来验证类别的存在,并且您已经为路径/404声明了一个路由


最后一点注意:如果您需要为current:category预加载一些数据,我会将这段代码放入解析中。这样,您就可以在一个地方完成所有操作:预加载数据,或者如果找不到/预加载数据,则重定向到/404。

您可能正在寻找守卫,因此我需要将404路由路径从**更改为404?啊,我在您的代码中错过了**路由。好吧,如果您希望能够显式地将用户重定向到未找到的页面,那么是的,最好有一个特定的路径,比如404。您可以将**路由重定向到:“404”。