【问题标题】:Adding Parameter to Angular router.navigate向 Angular router.navigate 添加参数
【发布时间】:2025-12-28 05:50:15
【问题描述】:

首先,我不确定这是否是实现我想要的正确方法.. 我正在尝试将如下导出绑定添加到 router.navigate()-method:

<call [caller]="caller"></call>

问题是我从不使用该指令,而是通过路由器对其进行寻址:

acceptCall() {
   this.router.navigate(["call"]);
}

如何在 acceptCall() 方法中实现与第一个示例相同的导出绑定? 我已经添加了一个 Input() 变量并使用 queryParams 进行了尝试,如下所示:

@Input() caller: Caller;
acceptCall(caller) {
    this.router.navigate(["call"], {queryParams: caller});
}

但这不起作用。

【问题讨论】:

  • 几乎!试试this.router.navigate(["call", caller]);
  • 对我不起作用,我必须修改我的 RouterModule.forRoot 吗?我的目前看起来像:{ path: 'call', component: CallComponent }
  • 嗯,是的,{path: 'call/:caller'} 你可以在你的子组件中使用this.route.params.subscribe((params: Params) =&gt; this.myParam = params['caller']); 来获取它(路由是一个ActivatedRoute)
  • 我已经更新了我的模块,但还没有完全了解其他内容 :D 你在哪里声明 Params ,myParam?您能否提供该类的完整代码示例作为答案?
  • @reveN:你的代码是如何组织的并不是很明显。如果您清楚地说明您提供的所有代码的位置,会更容易为您提供帮助。

标签: angular typescript binding router


【解决方案1】:

按照我的 cmets 你必须:

1 - 重新定义您的路线

{path: 'call/:caller', component: MyComponent }

2 - 在父组件中更改导航

this.router.navigate(["call", caller]);

3 - 在子组件中,获取参数

import { ActivatedRoute } from '@angular/router';
// code until ...
myParam: string;
constructor(private route: ActivatedRoute) {}
// code until ...
ngOnInit() {
    this.route.params.subscribe((params: Params) => this.myParam = params['caller']);
}

【讨论】:

  • mhh 我已经按照你说的做了所有事情,但是当我调用该方法时,我的路由器根现在回到了我的“家”组件而不是调用组件
  • 我使用像this.router.navigate(['../user', id], { relativeTo: this.route }); 这样的调用来确保它会重定向到正确的网址。可以试试吗?
  • 我创建了一个模拟调用程序并收到以下错误:错误:无法匹配任何路由。 URL 段:'call;Id=1;Name=Frodo%20Baggins;Tel=12345%2F678910;Company=The%20Fellowship%20of%20the%20Ring'
  • 哦!然后使用服务或父子关系。路由参数不是为此而设计的。
  • 为了完整起见,还需要从@angular/router 导入Params