【问题标题】:How to define a Route which takes optional parameter in Angular?如何在 Angular 中定义采用可选参数的 Route?
【发布时间】:2018-10-25 12:29:01
【问题描述】:

在互联网上进行了大量研究并在路由上通过Offical Angular Doc 之后,我还没有找到一个可行的解决方案,所以在这里发布这个问题,我不知道我是问错了还是完全不同步在这里,请多多包涵,我是 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

【问题讨论】:

  • this.router.navigate(['/products'], { queryParams: { order: 'popular' } });使用这个
  • alligator.io/angular/query-parameters此链接可能对您有所帮助
  • stackoverflow.com/a/44865817/10046738查看接受的答案
  • 你可以尝试为路由{path: 'game/:width',component: GameComponent}创建一个新路径
  • @jmdavalos 感谢这个链接很有帮助,所以最终的解决方案是我不需要在定义路由时做任何更改。只需在路由器链接中发送参数,如 ['/game',{width: 50, height:70}] 将发送参数,我可以在路由应用程序中订阅该参数,如 ActivatedRoute.params.subscribe(params => {} ) 这将为我提供参数,最终链接将是 localhost:4200/game;width=50;height=80

标签: angular angular-routing


【解决方案1】:

不太确定它是否会起作用以及它是否是一条好路,但我会尝试为同一个 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 路径,或者像这样的带有 Snapshot 系统的 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
}

链接:Angular Routing: Route Parameters

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 2018-11-28
    • 2015-01-28
    • 2018-02-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2017-05-02
    • 2012-08-08
    相关资源
    最近更新 更多