从 URL 中获取 Query 参数到 Component

传送门

我试图了解如何将 Query 参数从 URl 获取到我的组件中。以下是我尝试过的,我设置了app-routing.module.ts类似的路线

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

当我调试它时,我在日志中未定义

在此处输入图片说明

我在这里错过了什么

紧张

你需要改变你的路线

{
      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' },
  }

和网址应该是 yourhost/projectshipment?userid=231

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章