【问题标题】:Using Observables and Filtering an Array List in Angular App在 Angular App 中使用 Observables 和过滤数组列表
【发布时间】:2017-09-13 14:40:06
【问题描述】:

我在我的 Angular 应用程序中使用 observables,它按预期工作。但是,我遇到了一种有点令人困惑的情况。在一个组件中,我成功订阅了 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);

但是,在另一个组件中,虽然我在做几乎相同的事情,但我在控制台上打印了一个错误,内容如下:

例外:_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;
}

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

【问题讨论】:

  • 如果您在每种情况下都将鼠标悬停在 this.records 上,您会看到数据类型吗?这两个例子有什么不同吗?
  • 它们看起来一样:(属性)ConsultingComponent.records: any[]
  • "records" 在两个组件中都设置为空数组。

标签: javascript arrays angular filter


【解决方案1】:

由于是异步的,可以使用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;,因为您会收到未定义的错误。

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

【讨论】:

  • 仍然出现同样的错误。此外,如果异步是问题所在,那么这对双方来说肯定都是一个问题。我的意思是,第二个示例返回一个错误,而第一个没有。
【解决方案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

【讨论】:

  • 不管怎样 - 问题是,为什么第二个示例返回错误,而第一个不返回?在这两种情况下,我都会在订阅后进行过滤。所以这不是问题。
  • 如果结果是单个项目,过滤器将不适用于数组。你确定你在那里收藏吗?可以放一个console.log
  • 非常有趣。令我惊讶的是,这奏效了!非常感谢!
猜你喜欢
  • 2018-01-15
  • 2019-07-31
  • 2018-07-11
  • 2019-03-03
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
相关资源
最近更新 更多