Muirik
Muirik

Reputation: 6289

Using Observables and Filtering an Array List in Angular App

I am using observables in my Angular app, and it's working as expected. However, I am running into one situation that's a little confusing. In one component I am successfully subscribing to the observable, and then filtering the results, like this:

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);

However, in another component, while I am doing virtually the same thing, I am getting an error printed to the console that reads:

EXCEPTION: _this.records.filter is not a function

This what that component looks like:

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;
}

What's the issue in the second case? Why am I getting the error there and not in the first case?

Upvotes: 1

Views: 1203

Answers (2)

Aravind
Aravind

Reputation: 41553

It is because of the async nature, you can use skipWhile operator to

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});

Note : Make sure that this.records=[]; is instantiated

Update : You should not assign this.records=this.OTRecords; inside the subscription because of which you got the undefined error.

In the first case filtered elements might contain more than one object(array) but not in the second case

Upvotes: 0

Ovais
Ovais

Reputation: 384

Why not filter before you subscribe

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

I believe Angular uses RxJS, take reference from http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-filter

Upvotes: 2

Related Questions