gpt4 book ai didi

javascript - 错误 TypeError : array. map 不是 Angular 管道中的函数

转载 作者:行者123 更新时间:2023-12-02 22:14:20 25 4
gpt4 key购买 nike

我在使用此 Angular 管道时收到此错误 ERROR TypeError: ERROR TypeError: array.map is not a function 错误,这里是代码。

export class CharacterWithCommasPipe implements PipeTransform {
transform(array) {
return array.map(item => item.name).join(', ');
}

}

enter image description here

最佳答案

您可能没有在数组上调用此管道。

理想情况下,您应该确保在管道的输入不符合预期格式时抛出错误。这样就会以更优雅的方式实现

为此,请对管道进行以下更改:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
name: "joiner"
})
export class JoinerPipe implements PipeTransform {
transform(arrayToJoin: Array<any>, joinBy?: string) {
if (arrayToJoin && arrayToJoin.map) {
return arrayToJoin.map(item => item.name).join(joinBy || ", ");
}
throw new Error('joiner pipe only expects an Array as a first argument');
}
}

然后你可以像这样使用它:

<p> With Joiner Value - {{ items | joiner: ' and ' }}</p>
<p> Without Joiner Value - {{ items | joiner }}</p>

<p> With wrong Input that throws error on the console - {{ someOtherItems | joiner: ', ' }}</p>

在看起来像这样的数据上:

items = [
{ name: 'A' },
{ name: 'B' },
{ name: 'C' },
{ name: 'D' }
];

someOtherItems = 'ABCD';
<小时/>

Here's a Working Sample Demo Code for your ref.

关于javascript - 错误 TypeError : array. map 不是 Angular 管道中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59443664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com