如何将参数传递到URL内的routerLink?


Answers:


347

在您的特定示例中,您将执行以下操作routerLink

[routerLink]="['user', user.id, 'details']"

为此,可以在控制器中注入Router和使用:

router.navigate(['user', user.id, 'details']);

路由和导航”的“ Angular文档链接参数数组”部分中的更多信息


您可以提供任何链接以找到更多有关此信息的信息吗?
重构

4
:@CleanCrispCode你可以阅读更多关于它在路由器引导角文档angular.io/docs/ts/latest/guide/...
沃伊切赫Kwiatek

怎么样的<button mat-button routerLink="...">View user</button>语法?
Stephane

33

也许这是很晚的答案,但是如果您想使用参数浏览另一个页面,可以,

[routerLink]="['/user', user.id, 'details']"

同样,您也不应忘记路由配置,例如

 [path: 'user/:id/details', component:userComponent, pathMatch: 'full']

11

首先在表中配置:

const routes: Routes = [  
{
  path: 'class/:id/enrollment/:guid',
  component: ClassEnrollmentComponent
 }
];

现在输入脚本代码:

this.router.navigate([`class/${classId}/enrollment/${4545455}`]);

在另一个组件中接收参数

 this.activatedRoute.params.subscribe(params => {
  let id = params['id'];
  let guid = params['guid'];

  console.log(`${id},${guid}`);
  });

0

有多种方法可以实现这一目标。

  • 通过[routerLink]指令
  • Router类的navigation(Array)方法
  • navigationByUrl(string)方法,它接受一个字符串并返回一个Promise

routerLink属性要求您将routingModule导入功能模块,以防您延迟加载功能模块;或者如果未自动将其添加到AppModule导入数组中,则仅导入app-routing-module。

  • 路由器链接
<a [routerLink]="['/user', user.id]">John Doe</a>
<a routerLink="urlString">John Doe</a> // urlString is computed in your component
  • 导航
// Inject Router into your component
// Inject ActivatedRoute into your component. This will allow the route to be done related to the current url
this._router.navigate(['user',user.id], {relativeTo: this._activatedRoute})
  • NavigateByUrl
this._router.navigateByUrl(urlString).then((bool) => {}).catch()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.