Angular2 - 将数据从订阅的observable推送到数组

时间:2017-07-12 17:56:42

标签: angular typescript

我有一个订阅Subject的组件,并在点击按钮时接收数据。

我将这些数据存储在一个数组中,一切正常。但是,我试图只将新数据推送到数组而不是已经存在的任何重复数据。

我使用lodash方法使用_uniqBy完成了此操作。

我的问题是,每次按下按钮时它都会覆盖我的importResults数组,而不是仅将数据推送到不存在的数据。

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

当我尝试使用push时,我收到错误ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined

我的最终目标是,如果数据不存在,我只想将数据推送到importResults,而不是覆盖整个数据。

更新

importResults: ImportResults[];更改为importResults: ImportResults[] = [];似乎已更改了我的数据结构,现在*ngFor未显示数据。

在初始化之前:

enter image description here

初始化后:

enter image description here

HTML:

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

</tr>

1 个答案:

答案 0 :(得分:1)

问题是你只声明了变量而没有初始化,这就是它抛出错误的原因。

刚刚更新 -

 importResults: ImportResults[] =[] ;

这可以解决您的问题。

<强>更新 正如你所说的那样推送数据会改变你必须对每个结果做的结构。 E. G

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