【问题标题】:custom filter pipe in ngfor ~ ERROR TypeError: Cannot read property 'filter' of undefinedngfor 中的自定义过滤器管道〜错误类型错误:无法读取未定义的属性“过滤器”
【发布时间】:2018-02-09 14:45:13
【问题描述】:

我正在开发一个用于 ngFor 循环的过滤器,但遇到了一个错误以及另一个问题。

我的管道看起来很简单。我正在传递一个 id 号的参数以进行过滤,然后将其与对象属性之一进行比较:

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

@Pipe({
    name: 'groupBy'
})

export class GroupByPipe implements PipeTransform {

    transform(items: any, groupId: number ): any {
        console.log(groupId);
        items.filter(items => items.storyFunnelStatusId === groupId);
    }

}

然后我的模板从前一个循环中获取 column.id 作为过滤器的参数:

<div class="board-container">
    <div class="board-column" *ngFor="let column of columnNames">
        <div class="board-heading">
            {{ column.name }}
            <span class="count">4</span>
        </div>
        <div id="column-{{ column.id }}" class="card-body">
            <div *ngFor="let item of results | groupBy: column.id">
                <pre>{{ item | json }}</pre>
            </div>
        </div>
    </div>
</div>

两个问题,第一个大问题是我收到控制台错误:ERROR TypeError: Cannot read property 'filter' of undefined

第二个是当我尝试console.log('groupId') 时,我得到了 10 个结果,而我应该只得到一个。

要把我的头发拉出来:(

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    ERROR TypeError: Cannot read property 'filter' of undefined 表示您在GroupByPipe 中的items 未定义,这意味着您向其传递了错误的参数。

    通过修改您的模板将修复它。

    <div class="board-container">
        <div class="board-column" *ngFor="let column of columnNames">
            <div class="board-heading">
                {{ column.name }}
                <span class="count">4</span>
            </div>
            <div id="column-{{ column.id }}" class="card-body">
                <div *ngFor="let item of (results | groupBy: column.id)">
                    <pre>{{ item | json }}</pre>
                </div>
            </div>
        </div>
    </div>
    

    因为let item of results 成为您发送到管道的第一个参数,而这个表达式的值是undefined


    与此同时,您可以像这样在管道的实现中添加一些安全检查:

    transform(items: [any], groupId: number ): any {
        console.log(groupId);
        if(items instanceof Array) {
            return items.filter(items => items.storyFunnelStatusId === groupId);
        }
        return [];
    }
    

    【讨论】:

    • 很酷,谢谢,所以现在至少可以让过滤器工作,这意味着我可以看到数据,但我仍然收到未定义的错误?
    • @SandraWillford 这很简单。还有一些undefine检查可以解决...我会更新答案。
    猜你喜欢
    • 2021-12-31
    • 2017-06-27
    • 2019-03-13
    • 2020-01-12
    • 2020-10-22
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多