如何将参数传递给 URL 内某处的 routerLink?

How to pass a parameter to routerLink that is somewhere inside the URL?

我知道我可以将参数传递给 routerLink 用于路由

/user/:id

通过写作

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

但是像这条路线呢:

/user/:id/details

有没有办法设置这个参数,或者我应该考虑不同的 URL 方案?

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

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

要在控制器中执行此操作,您可以注入 Router 并使用:

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

Angular 文档中的更多信息Link Parameters Array section of Routing & Navigation

也许这真的是迟到的答案,但如果你想用参数导航另一个页面,你可以,

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

你也不应该忘记路由配置,

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

首先在table配置:

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}`);
  });

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

  • 通过 [routerLink] 指令
  • Router的navigate(Array)方法class
  • navigateByUrl(string) 方法接受一个字符串和 returns 一个 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()
constructor(private activatedRoute: ActivatedRoute) {

this.activatedRoute.queryParams.subscribe(params => {
  console.log(params['type'])
  });  }

这对我有用!

app-routing.module.ts

const routes: Routes = [
  { path: 'products', component: ProductsComponent },
  { path: 'product/:id', component: ProductDetailsComponent },
  { path: '', redirectTo: '/products', pathMatch: 'full' },
];

在控制器中,您可以像这样导航,

this.router.navigate(['/products', productId]);

它会让你进入这样的路径:http://localhost:4200/products/product-id

constructor(private activatedRoute: ActivatedRoute) {}

在您使用的情况下

`this.activatedRoute.parmas.subscribe(params => { console.log(params['type']) }); }`

so params 而不是 queryparamas 从 url –

获取参数

很简单

<a routerLink="/user/{{id}}/details"></a>

您可以使用动态值生成 link。对于动态 link,传递一组路径段,然后是每个段的参数。 例如,['/team', teamId, 'user', userName, {details: true}] 生成一个 link 到 /team/11/user/bob;details=true.