Angular2 - 将数据推送到具有接口的阵列

时间:2017-07-10 14:36:46

标签: angular

我有一个组件通过subscribe从服务接收数据。我将此数据存储为array,然后使用*ngFor对其进行循环并在表格中显示结果。

问题是,每次单击按钮时,我都不想覆盖此数组,而只是想推送它,这样它就不会消除已经在页面上显示的数据。

组件:

import { ImportResults } from '../shared/mass.interface';
import { Component, Input, OnChanges, OnInit } from '@angular/core';
import { MassEmpService } from '../shared/mass.service';

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

export class EmployeeSelectionComponent implements OnInit {

    // Define our search results
    public searchResults: ImportResults[];

    constructor(
        private _massEmpService: MassEmpService
    ) {
    }

    ngOnInit() {

        this._massEmpService.importedResults.subscribe(
            data => this.searchResults = data
        );

    }
}

服务

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { RouterLink } from '@angular/router';
import { FrameworkService } from '@aps/framework';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class MassEmpService {

    // API URL
    baseUrl = 'https://internal-site/api';

    // Define the token headers for the service calls
    headers: Headers = new Headers({
        "Authorization": this._frameworkService.getSessionInfo().token
    });

    // Create a subject to observe the results and changes over time
    public importedResults = new Subject<any>();

    constructor(
        private _http: Http,
        private _frameworkService: FrameworkService
    ) { }

    // Given a dataset, return the users based on data points submitted
    processImport(dataType, dataSet): Observable<any> {
        return this._http.post(this.baseUrl + '/fetchEmployeesFromImport', { "dataType": dataType, "data": dataSet }, { "headers": this.headers })
            .map((result: Response) => result.json())
            .share()
            .catch(this.handleError);
    };

    // Pass the data received from the import process through our subject to observe
    fetchImportedResults(data){
        this.importedResults.next(data);
    }

    private handleError(error: Response): Observable<any> {
        console.log(error);
        return Observable.throw(error.json() || 'Server Issue');
    }

}

问题

在组件中,我将this.searchResults设置为提取的结果。每次调用时,它都会覆盖结果。我需要将这些数据推送到数组中,如果它不存在而不是每次都被覆盖。

我尝试过什么

我尝试通过执行public searchResults: ImportResults[] = [];然后使用data => this.searchResults.push(data)来初始化数组。虽然这不会引发错误,但我循环的表不再呈现数据。我相信这是因为它现在在另一个阵列中。

这是我尝试使用PUSH之前的数据。我猜测当我推动它时,它改变了结构,所以*ngFor现在没有正确循环。 This is what my data looks like before I try to use PUSH

1 个答案:

答案 0 :(得分:2)

问题在于您将整个数组推送到结果数组而不是单个对象。尝试将spread运算符与push结合使用,将新项添加到数组中,如下所示:

data => this.searchResults.push(...data)