简体   繁体   中英

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. In the data service the results are being pushed onto an array named _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. I am very new to Javascript, and asking for help to ensure that any additional calls to data service only return unique data. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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