简体   繁体   English

如何正确重新初始化返回的数据数组

[英]How to properly re-initialize an array of returned data

In my single page Angular app I have a controller, which makes calls to a data service. 在我的单页Angular应用程序中,我有一个控制器,该控制器调用数据服务。 In the data service the results are being pushed onto an array named _result. 在数据服务中,结果被推送到名为_result的数组上。 On any subsequent calls to the data service, the _result array is being appended to, instead of being emptied out first, which results in a duplicate data being passed to the controller and displayed in a view. 在对数据服务的任何后续调用中,_result数组将附加到而不是先清空,这导致重复的数据被传递到控制器并显示在视图中。 I am very new to Javascript, and asking for help to ensure that any additional calls to data service only return unique data. 我是Java的新手,请寻求帮助以确保对数据服务的任何其他调用仅返回唯一数据。 Here is my controller: 这是我的控制器:

angular.module('frontEndApp').controller('ViewExistingRequestsCtrl', ['$scope', 'requestsRepository',
    function ($scope, requestsRepository) {

        $scope.sendrequest = requestsRepository.getServiceRequests();

        $scope.requests = requestsRepository.result;

    }]
);

And here is my data service, which has the _result array: 这是我的数据服务,它具有_result数组:

frontEndApp.factory('requestsRepository',function ($http) {
    var _result = [];
    var postServiceRequest = function (ServiceRequest) {
        $http(
        {
            url: 'http://localhost:8080/api/ServiceRequests', method: "POST", data: ServiceRequest,
            headers: {
                'Content-Type': 'application/json'
            }
        }).success(function (data, status, headers, config) {
            console.log("postServiceRequest Status: " + status);
        }).error(function (data, status, headers, config) {
            console.log("postServiceRequest FAILURE: " + status + "  ServiceRequest:  " + ServiceRequest);
        });
    };
    var getServiceRequests = function () {
        $http({
            method: 'GET', url: 'http://localhost:8080/api/ServiceRequests'
        }).success(function (data, status, headers, config) {

            for (var key in data) {
                _result.push(data[key]);
            } console.log(_result)
            return _result;
        }).error(function (data, status, headers, config) {
            return status;
        });
    };
    return {
        postServiceRequest: postServiceRequest, getServiceRequests: getServiceRequests, result: _result
    };
});

Just redefine it as an empty array before populating it: 只需在填充它之前将其重新定义为一个空数组即可:

...

$http({
        method: 'GET', url: 'http://localhost:8080/api/ServiceRequests'
    }).success(function (data, status, headers, config) {
        _result = []; // <---- this is the key!
        for (var key in data) {
            _result.push(data[key]);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM