在Angular2中传递多个路径参数

use*_*623 60 angular2-routing angular

是否有可能通过多种途径PARAMS比如像下面需要传递id1id2component B

@RouteConfig([
    {path: '/component/:id :id2',name: 'MyCompB', component:MyCompB }
])
export class MyCompA {
  onClick(){
    this._router.navigate( ['MyCompB', {id: "someId", id2: "another ID"}]);
     }
}
Run Code Online (Sandbox Code Playgroud)

use*_*623 61

好意识到了一个错误..它必须是 /:id/:id2

无论如何,在任何教程或其他StackOverflow问题中都没有找到它.

@RouteConfig([{path: '/component/:id/:id2',name: 'MyCompB', component:MyCompB}])
export class MyCompA {
    onClick(){
        this._router.navigate( ['MyCompB', {id: "someId", id2: "another ID"}]);
    }
}
Run Code Online (Sandbox Code Playgroud)


tre*_*eat 48

如本回答所述,mayur&user3869623的答案现在与弃用的路由器有关.您现在可以传递多个参数,如下所示:

要呼叫路由器:

this.router.navigate(['/myUrlPath', "someId", "another ID"]);
Run Code Online (Sandbox Code Playgroud)

在routes.ts中:

{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},
Run Code Online (Sandbox Code Playgroud)

  • 对于任何想要了解的人,也可以在这些ID变量之间添加一些其他术语,这有助于创建更加用户友好的URL.示例:this.router.navigate(['/ mypath',"firstId","secondPath","secondID"]),允许'myPath/4/secondPath/5' (5认同)
  • @EamonBohan你救了我整整一天的调查,你真正的MVP,谢谢你! (3认同)

SUB*_*DAN 14

Angular 中传递多个路由参数的两种方法

方法一

在 app.module.ts

将路径设置为 component2。

imports: [
 RouterModule.forRoot(
 [ {path: 'component2/:id1/:id2', component: MyComp2}])
]
Run Code Online (Sandbox Code Playgroud)

使用多个参数 id1 和 id2 调用路由器导航到 MyComp2。

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', "id1","id2"]);
 }
}
Run Code Online (Sandbox Code Playgroud)

方法二

在 app.module.ts

将路径设置为 component2。

imports: [
 RouterModule.forRoot(
 [ {path: 'component2', component: MyComp2}])
]
Run Code Online (Sandbox Code Playgroud)

使用多个参数 id1 和 id2 调用路由器导航到 MyComp2。

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', {id1: "id1 Value", id2: 
    "id2  Value"}]);
 }
}
Run Code Online (Sandbox Code Playgroud)