【问题标题】:route.queryParams.subscribe returns undefined in Angular Typescript Componentroute.queryParams.subscribe 在 Angular Typescript 组件中返回 undefined
【发布时间】:2021-01-09 07:38:21
【问题描述】:

我需要将 id 作为参数传递给我的角度组件

在我的 html 中我有这样的东西

<a [routerLink]="['/viewjobdetail',  currentJob.id]">
    {{ currentJob.title }}
</a>

app.module.ts RouterModule.forRoot 配置为

  { path: 'viewjobdetail/:id', component: JobDetailComponent }

在我的调用组件中,我有

import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute){}

ngOnInit(): void {
this.route.queryParams.subscribe(params => {
  debugger;
  var a = params['id'];
  this.displayJobId = parseInt(params['id']);
});

但是当我检查它时它总是显示 undefined for a,我在这里做错了什么? }

【问题讨论】:

    标签: angular typescript url-routing angular2-routing


    【解决方案1】:

    您应该使用paramsparamMap 而不是queryParams,查询参数只能识别像viewjobdetail?id=23 这样传递的查询参数

    queryParams 更好,因为params 可能会在未来的版本中被弃用

    this.route.paramMap.subscribe(paramMap => {
      debugger;
      var a = paramMap.get('id');
      this.displayJobId = parseInt(a);
    });
    

    【讨论】:

    • 所以如果我要使用 queryParams,我应该如何在我的 html 标签中声明它?
    • @NithinPaul 如果您想在 HTML 中使用 queryParams,请按照this post中的说明使用它
    • 刚刚更新了我的答案中的代码,我错误地使用了 queryParams 而不是 paramMap,除了 Ruben 评论之外,如果您使用了 paramMap,则不需要更改 html 中的任何内容
    【解决方案2】:

    我得到了解决方案。为了实现这一点,我们需要使用带有 queryParams 的查询参数。我修改了我的html如下

    <a [routerLink]="['/viewjobdetail']" [queryParams]="{id: currentJob.id}">
    {{ currentJob.title }}
    </a>
    

    在 app.module.ts 中

    { path: 'viewjobdetail', component: JobDetailComponent }
    

    然后在我的调用组件中

      this.route.queryParams.subscribe(params => {
      
      var a = params.id;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 2021-05-06
      • 2017-10-13
      相关资源
      最近更新 更多