【问题标题】:How to navigate to a route with query param but without showing ? and = in the URL如何导航到带有查询参数但不显示的路线?和 = 在 URL 中
【发布时间】:2023-01-06 22:28:09
【问题描述】:

我从来没有在 Angular 中实现过路由。我的要求是在从父组件单击图标时导航到详细信息页面。这是我的代码:

产品.component.ts

  // method called when the corresponding pencil/edit icon is clicked
  loadSingleRecord() {
    this._router.navigate(['products/electronic/billing/'], {
      queryParams: { id: 12 }, // let it be id 12 for sometime
    });
  }

产品路由.module.ts

const routes: Routes = [
  ...
  {
    path: 'electronic/billing/:id',
    component: BillingSingleRecordComponent,
  },
  ...
];

@NgModule({
  imports: [RouterModule.forChild(routes), HttpClientModule],
  exports: [RouterModule],
})
export class ProductsRoutingModule {}

这个逻辑工作正常:

localhost:4205/products/electronic/billing/record?id=29

但我不想显示?id=29。能不能这么简单:localhost:4205/products/electronic/billing/record/29。请帮忙。

我忘了提到在到达详细信息组件时我也想要 id:

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe((params) => {
      let id = params['id'];
      console.log(id); // OUTPUT undefined
    });

【问题讨论】:

    标签: angular


    【解决方案1】:

    electronic/billing/:id 路径中的:id 不是查询参数,而是路由参数(也称为路径变量)。查看this tutorial了解更多信息

    当你导航时,你应该使用

    this._router.navigate(['products/electronic/billing', id]);
    

    如果你想在你的组件中阅读这个,你可以使用

    ngOnInit(): void {
        this.activatedRoute.params.subscribe((params) => {
            let id = params['id'];
            console.log(id);
        });
    }
    

    【讨论】:

    • 抱歉,我忘了提到我需要在详细信息组件中获取该 ID。我在问题中添加了一个新部分。你能帮忙吗?
    • 我已经更新了我的回复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2018-06-12
    相关资源
    最近更新 更多