【问题标题】:ERROR TypeError: array.map is not a function in angular pipe错误类型错误:array.map 不是角度管道中的函数
【发布时间】:2020-04-14 01:18:14
【问题描述】:

我收到此错误 ERROR TypeError: ERROR TypeError: array.map is not a function error while using this angular pipe and here is code.

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

}

【问题讨论】:

  • 请同时发布使用此管道的视图代码,您很可能将一些不是数组的东西放入管道中
  • 对象,{},在 JavaScript 中没有方法 .map()。所以请确保它。

标签: javascript angular angular8 angular-pipe


【解决方案1】:

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

理想情况下,如果管道的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';

这里有一个Working Sample Demo Code 供您参考。

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 2018-12-03
    • 2022-01-21
    • 2019-11-30
    • 2021-06-01
    • 2019-10-07
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    相关资源
    最近更新 更多