Angular 在路线4中传递多个参数

Angular 在路线4中传递多个参数,angular,angular2-routing,Angular,Angular2 Routing,您好,我想在angular 4中传递一些带有路由的参数 app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { StartGameComponent } from './start-game/start-game.component'; import { GameComponent } from

您好,我想在angular 4中传递一些带有路由的参数

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { StartGameComponent } from './start-game/start-game.component';
import { GameComponent } from './game/game.component';


const appRoutes: Routes = [
  { path: '', redirectTo: '/first', pathMatch: 'full' },
  { path: 'startGame', component: StartGameComponent },
  {path: 'game/:width/:height',component: GameComponent
  }

];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule {

}
在组件开始时组件

      goToGameComponent(width:string,height:string){
      this.router.navigate(['game', {width:width,height:height}]);
}
在组件游戏组件中

 ngOnInit() {
        this.route.params.forEach((urlParams) => {
          this.width= urlParams['width'];
          this.height=urlParams['height'];

        });
在app.component.html中

<div>
  <md-toolbar color="primary">
    <span>MineSweeper Wix</span>

  </md-toolbar>
  <router-outlet></router-outlet>

  <span class="done">
    <button md-fab>
      <md-icon>check circle</md-icon>
    </button>
  </span>
</div>

扫雷舰Wix
检查圈
这是我的错误

无法匹配任何路由。URL段:'游戏;宽度=10;高度=10'


您将所需路由参数的语法与可选路由参数混合使用

Angular提供三种类型的管线参数: 1) 所需参数。 2) 可选参数。 3) 查询参数

必需的参数用于必需的值,例如显示详细信息页面的Id。您的箱子需要宽度和高度吗

可选参数用于并非总是必需的值,例如将输入的搜索条件传递给应使用该条件的列表页

查询参数与可选参数类似,但您可以跨管线保留它们。因此,如果您想在某处布线并再次布线,可以保留参数

路由配置中仅定义了必需的参数。路由配置中不包括可选参数和查询参数(因此路径将只是“游戏”)

根据类型的不同,设置参数的语法也不同:

所需参数:
this.router.navigate(['game',width,height])

可选参数:
this.router.navigate(['game',{width:width,height:height}])

查询参数:
this.router.navigate(['game',{queryParams:{width:width,height:height}}])


有关更多信息,请查看:

我需要传递动态构造它们的多个查询参数。因此,请执行以下步骤以实现相同的目标:

例如

const arrayItem=[{source:“external”},{fileFiler:“File Name 1”}];
const queryParams=arrayItem.reduce((arrObj,item)=>Object.assign(arrObj,item,{}));//这将转换为单个对象。

//输出:{source:“external”,filer:“File Name 1”}
感谢您的精彩解释,它帮助我解决了我的问题。如何从另一端获取参数?我的意思是,从您导航到的组件?@DeborahK如何传递一个字符串参数,该参数中有空格,如“进程1”?如果我的第二个参数是可选的,该怎么办?@knigalye您将所需参数作为必需参数处理,将可选参数作为可选参数处理。比如:
this.router.navigate(['game',game.id,{height:height}])