首页 > 解决方案 > 如何在 Angular 中定义采用可选参数的 Route?

问题描述

在互联网上进行了大量研究并通过Offical Angular Doc on Routing 之后,我还没有找到一个可行的解决方案,所以在这里发布这个问题,我不知道我是问错了还是完全不同步所以请忍耐对我来说,我是 Angular 的新手。

基本上我想定义一个带有多个可选参数的路由。

在我的路由模块中,我正在定义这样的路由

const appRoutes: Routes = [
  {path: 'game/:width/:height',component: GameComponent
}];

如果我是导航到https://localhost:4200/game/50/80,这很好用

但 为https://localhost:4200/game/50/给出“无法匹配任何路由异常”

我如何定义可以两种方式工作的路线(有/没有高度)

即使是使用查询参数的解决方案也可以,例如https://localhost:4200/?width=50&height=80

标签: angularangular-routing

解决方案


不确定它是否会起作用以及它是否是一条好路,但我会尝试为同一个 GameComponent 创建一些子路由,如下所示:

const appRoutes: Routes = [
{
  path: 'game',
  children: [
     { path: '', component: GameComponent },
     { path: ':width', component: GameComponent },
     { path: ':width/:height', component: GameComponent }
  ]
}];

所以我可以使用 /game /game/50 和 /game/50/80 并且我会根据情况在参数上使用一些条件来管理 GameComponent ngOnInit 中的逻辑:

width: number;
height: number;

ngOnInit() {

   this.route.paramMap.subscribe(params => {
         if (params['width'] && params['height']) {
          this.width = +params['width'];  // + converts string 'width' to a number
          this.height = +params['height'];
          // /game/50/80 - do something
        } else if (params['width']) {
          this.width = +params['width'];
          // /game/50 - do something
        } else {
          // /game - do something
        }
   }

}

然后我可以解决 this.width !this.width 和 this.height !this.height 来处理我的组件中的不同场景

否则我也会以同样的方式探索 queryParamMap 路径,或者像这样带有快照系统的 ActivatedRoute:

this.width = this.route.snapshot.paramMap.get('width');
this.height = this.route.snapshot.paramMap.get('height');

if (this.width && this.height) {
  // do something
} else if (this.width && !this.height) {
  // do something
} else {
  // /game
}

链接:角度路由:路由参数


推荐阅读