使用管道在Angular 2中过滤对象数组

3

I have a

class:

export class Todo {
    public id: number;
    public name: string;
    public isCompleted: boolean;
    public dateCreated: Date;
    public userName: string;
}

一个服务:

getTodos(): Observable < Todo[] > {
    return this.http.get(this.todosUrl)
        .map(this.extractData)
        .catch(this.handleError);
}

private extractData(res: Response) {
    let body = res.json();
    return body || {};
}

在我的组件中:
getTodos(){
    this.todoService.getTodos()
      .subscribe(
        todos => this.todos = todos,
        error => this.errorMessage = <any>error
      );
}

还有HTML文件:

<div class="ui large selection animated divided list">
    <a *ngFor="let todo of (todos | todoFilter:false)" class="item">
        <div class="right floated content">
            <div class="ui vertical animated negative button" tabindex="0">
                <div class="hidden content">Delete</div>
                <div class="visible content">
                    <i class="fa fa-trash" aria-hidden="true"></i>
                </div>
            </div>
        </div>
        <i class="minus square outline icon"></i>
        <div class="content">
            <div class="header">{{todo.name}}</div>
            <div class="description">{{todo.dateCreated | date:"MMM-dd-yyyy"}}</div>
        </div>
    </a>
</div>

问题在于,当我尝试使用这个管道来过滤已完成的待办事项时,我一直收到一个错误提示,说无法读取属性filterundefined。 我做错了什么或者有没有其他方法可以在不使用pipe的情况下进行筛选?

我的管道:

transform(allTodos: Todo[], args?: boolean){
    if (allTodos === null) {
      return null;
    }
    return allTodos.filter(todo => todo.isCompleted);
}

谢谢你。

感谢您。

1个回答

2

尝试将 if (allTodos === null) 替换为 if (!allTodos)。 我认为问题在于,在检查它不为空之前,您甚至在您的 this.todos 还是空的时候就到了 .filter 中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接