从 URL 中获取 Query 参数到 Component

Get the Query parameter from the URL in to Component

我想了解如何从 URl 获取我的组件中的查询参数。下面是我试过的,我把路由设置在 app-routing.module.ts like

  {
      path: 'ProjectShipment/userId/231',
      component: ProjectShipmentComponent,
      data: { title: 'Project Shipment' },
  }

并且在 project-shipment.component.ts 我试过

import {Router, ActivatedRoute, Params} from '@angular/router';
export class ProjectShipmentComponent implements OnInit {

  constructor( private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    debugger;
    this.activatedRoute.queryParams.subscribe(params => {
      const userId = params['userId'];
      console.log(userId);
    });}}

当我调试它时,我在日志中得到 undefined

我在这里错过了什么

您需要将路线更改为

{
      path: 'ProjectShipment/:userId',
      component: ProjectShipmentComponent,
      data: { title: 'Project Shipment' },
  }

然后当你在你的组件中像yourhost/projectshipment/231那样调用它时

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

要获取查询参数,您的代码是正确的,但您的路线应该

{
      path: 'ProjectShipment',
      component: ProjectShipmentComponent,
      data: { title: 'Project Shipment' },
  }

和url应该是yourhost/projectshipment?userid=231