Typescript 过滤器在 Angular 中返回一个空数组
Typescript filter returning an empty array in Angular
我在 Angular 中有一个过滤函数,即 return 一个空数组。我知道以前有人问过类似的问题,我已经尝试了所有这些问题,但都失败了。该功能本身似乎是正确的。任何帮助将不胜感激。
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,
}
更新 更改 gift.id == this.id 到 gift.id == 22 做了 return 一个值。这意味着 this.id 没有被正确获取。不知道为什么...有什么想法吗?
过滤函数
this.currentGift = this.gifts.filter(gift => {
gift.id == this.id
})
没有 return 任何东西。它必须 return 一个布尔值:
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);
你必须使用 URL 像 localhost:4200/details-page/11
而不是 localhost:4200/details-page/:11
否则 params.get('id')
将被设置为 ':11'
而这个字符串显然不能转换为数字。
我在 Angular 中有一个过滤函数,即 return 一个空数组。我知道以前有人问过类似的问题,我已经尝试了所有这些问题,但都失败了。该功能本身似乎是正确的。任何帮助将不胜感激。
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,
}
更新 更改 gift.id == this.id 到 gift.id == 22 做了 return 一个值。这意味着 this.id 没有被正确获取。不知道为什么...有什么想法吗?
过滤函数
this.currentGift = this.gifts.filter(gift => {
gift.id == this.id
})
没有 return 任何东西。它必须 return 一个布尔值:
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);
你必须使用 URL 像 localhost:4200/details-page/11
而不是 localhost:4200/details-page/:11
否则 params.get('id')
将被设置为 ':11'
而这个字符串显然不能转换为数字。