我知道我可以为routerLink传递一个参数,例如

/user/:id

通过编写

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

但是像这样的路线呢:

/user/:id/details

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


当前回答

首先在表中配置:

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

其他回答

constructor(private activatedRoute: ActivatedRoute) {

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

这对我很管用!

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

通过[routerLink]指令 Router类的navigate(Array)方法 navigateByUrl(string)方法,它接受字符串并返回承诺

routerLink属性要求你将routingModule导入到特性模块中,以防你延迟加载了特性模块,或者如果app-routing-module没有自动添加到AppModule imports数组中,则直接导入。

RouterLink

<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()

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

Ref

首先在表中配置:

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

也许这个回答有点晚,但是如果你想用param浏览另一个页面,

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

此外,你不应该忘记路由配置,

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