SBB
SBB

Reputation: 8990

Angular2 - Pushing data to an array from a subscribed observable

I have a component that is subscribed to a Subject and receives data upon a button click.

I am storing this data in an array and all is working fine. However, I am trying to only push new data to the array instead of any duplicates that already exist.

I accomplished this with lodash using the _uniqBy method.

My issue is that it is overwriting my importResults array each time I press the button instead of only pushing data to it that doesn't already exist.

import { Component, Input, OnChanges, OnInit, NgModule } from '@angular/core';
import { MassEmpService } from '../shared';
import { ImportResults } from '../definitions';
import * as _ from "lodash";

@Component({
    selector: 'app-employee-selection',
    templateUrl: './employee-selection.component.html',
    styleUrls: ['./employee-selection.component.css']
})

export class EmployeeSelectionComponent implements OnInit {

    // Define our search results
    importResults: ImportResults[];

    constructor(
        private _massEmpService: MassEmpService
    ) {
    }

    ngOnInit() {
        // Subscribe to our subject that lets us know about the added employees
        this._massEmpService.importedData.subscribe(obj => {
            if (obj) {
                // Ensure that we have unique results in our imported data
                this.importResults.push(_.uniqBy(obj, 'QID'));
            }
        });
    }

    // On clear employees
    clearEmployees() {
        this._massEmpService.updateImportData(null);
    }
}

When I tried using push, I get the error of ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined.

My end goal here is that I only want to push data to importResults if it doesn't already exist in there, instead of overwriting the whole thing.

Update:

Changing importResults: ImportResults[]; to importResults: ImportResults[] = []; seems to have changed my data structure and now the *ngFor is not displaying the data.

Before the initialization:

enter image description here

After the initialization:

enter image description here

HTML:

<tr *ngFor="let i of importResults">

</tr>

Upvotes: 0

Views: 1715

Answers (1)

Faizal Shap
Faizal Shap

Reputation: 1820

The problem is that you have only declared the variable and not initialized which is why it is throwing error.

Just update -

 importResults: ImportResults[] =[] ;

This would fix your problem.

update As you said pushing data alters the structure you must do for each on the results then. E. G

_.uniqBy(obj, 'QID'). ForEach(p => this.importResults.push(p)); }

Upvotes: 1

Related Questions