在Angular App中使用Observable和过滤数组列表

时间:2017-04-17 22:26:12

标签: javascript arrays angular filter

我在Angular应用程序中使用了observable,它按预期工作。但是,我遇到了一个有点令人困惑的情况。在一个组件中,我成功订阅了observable,然后过滤结果,如下所示:

this.clientsService.getAll()
    .subscribe(resRecordsData => {
        this.records = resRecordsData;
        this.inactiveRecords = this.records.filter(record => record.category && record.category.includes('inactive'));
        this.records = this.inactiveRecords;
    },
    responseRecordsError => this.errorMsg = responseRecordsError);

然而,在另一个组件中,虽然我做的事情几乎相同,但我在控制台上输出的错误是:

  

EXCEPTION:_this.records.filter不是函数

该组件的外观如下:

optionReceived(option) {
    console.log('Consulting: ' + option.toolbarLabel);
    if (option.toolbarLabel === 'OT') {
        console.log('Consulting: OT Filter Activated!');
        this.clientService.getByCategory('consulting', 1, this.pagesize)
        .subscribe(resRecordsData => {
            this.records = resRecordsData;
            this.OTRecords = this.records.filter(record => record.type && record.type.includes('OT'));
            this.records = this.OTRecords;
        },
        responseRecordsError => this.errorMsg = responseRecordsError);
    } else {
        return this.records;
}

第二种情况的问题是什么?为什么我在那里得到错误而不是第一种情况?

2 个答案:

答案 0 :(得分:2)

为什么不在订阅前过滤

this.clientsService.getAll()
    .filter(record => record.category && record.category.includes('inactive'))
    .subscribe(
        resRecordsData => {
            this.records = resRecordsData;
        },
        err => this.errorMsg = err
    );

我相信Angular使用RxJS,参考http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-filter

答案 1 :(得分:0)

由于异步性质,您可以使用skipWhile运算符

this.clientService.getByCategory('consulting', 1, this.pagesize)
    .skipWhile(data => {
         if(data.length) {
             return false;
         }
     })
    .subscribe(resRecordsData => {
        this.records = resRecordsData;
        this.OTRecords = this.records.filter(record => record.type && record.type.includes('OT'));

    },
    ((responseRecordsError) => {this.errorMsg = responseRecordsError});

注意:确保this.records=[];已实例化

更新: 您不应在订阅中分配this.records=this.OTRecords;,因为您收到了未定义的错误。

在第一种情况下,过滤后的元素可能包含多个对象(数组),但在第二种情况下则不包含