ERROR TypeError: array.map is not a function in angular pipe

ERROR TypeError: array.map is not a function in angular pipe

我在使用此 angular 管道时收到此错误错误类型错误:错误类型错误:array.map 不是函数错误,这是代码。

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

}

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

理想情况下,如果管道的 input 不是预期的格式,您应该确保抛出错误。这样它会以更优雅的方式实现

为此对您的管道进行以下更改:

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.