【问题标题】:Typescript filter returning an empty array in AngularTypescript过滤器在Angular中返回一个空数组
【发布时间】:2021-05-06 17:35:53
【问题描述】:

我在 Angular 中有一个过滤函数,它返回一个空数组。我知道以前有人问过类似的问题,我已经尝试了所有这些问题,但都失败了。该功能本身似乎是正确的。任何帮助将不胜感激。

gifts 是一个礼品对象数组(见下文)

打字稿:

export class DetailsPageComponent implements OnInit {

  
  gifts: Array<Gift> = [ ... ]
  id: number
  currentGift: any

  constructor(private currentRoute: ActivatedRoute) { }

  ngOnInit(): void {

    this.currentRoute.paramMap.subscribe((params: ParamMap) => {
      this.id = +params.get('id')
      
      this.currentGift = this.gifts.filter(gift => {
        gift.id == this.id
      })
    })
  }

}

礼物对象:

{
name: 'giftName',
id: 22,
}

UPDATEgift.id == this.id 更改为 gift.id == 22 确实返回一个值。这意味着 this.id 没有被正确获取。不知道为什么...有什么想法吗?

【问题讨论】:

  • 你是在把 id 添加到 url 吗?
  • 是的,我是。它使用在另一个组件中单击的礼物的 i,并用作路由参数。在路由到该组件时,正确的 ID 在搜索栏中显示为“localhost:4200/details-page/:11”
  • 你试过 localhost:4200/details-page/11(没有分号)吗?
  • "localhost:4200/details-page/:11" 不,这是不正确的。它将params.get('id') 设置为':11' 并且这个字符串显然不能转换为数字。

标签: javascript angular typescript filtering


【解决方案1】:

过滤功能

this.currentGift = this.gifts.filter(gift => {
    gift.id == this.id
})

不返回任何内容。它必须返回一个布尔值:

this.currentGift = this.gifts.filter(gift => gift.id === this.id)

这是一个例子:

const gifts = [{
    name: 'giftName',
    id: 22,
}];

const id = +'22';

const currentGift = gifts.filter(gift => gift.id === id);

console.log(currentGift);

您必须使用localhost:4200/details-page/11 之类的网址而不是localhost:4200/details-page/:11,否则params.get('id') 将设置为':11',并且此字符串显然无法转换为数字。

【讨论】:

  • 仍然返回一个空数组。我觉得是身份证的问题。它将 this.id 显示为 Nan。
  • @SarmadHadi 我添加了一个示例,假设params.get('id') 返回一个有效数字作为字符串。如果它不起作用,则您未提供的代码中的其他地方还有另一个问题。你可以通过console.log(params.get('id'))查看。
  • 是的,我就是这么想的。
  • 完美运行。非常感谢。我很困惑,因为我必须在路由器模块中保留 :id 并在其他地方保留普通 id。
猜你喜欢
  • 2019-11-20
  • 1970-01-01
  • 2019-04-23
  • 2021-11-13
  • 2023-01-25
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多