如何在Angular中设置异步HTTP服务的回调,以便在不定义数组的情况下在控制器中填充数组

How can I set a callback to an asynchronous HTTP service in Angular so that I can fill my array in my controller without it being undefined?

本文关键字:数组 定义 情况下 填充 控制器 异步 设置 HTTP 服务 回调 Angular      更新时间:2024-04-24

如何在Angular中设置异步HTTP服务的回调,以便在不定义数组的情况下在控制器中填充数组

我的代码:

app.js

'use strict';
    var app = angular.module('app', ['ngRoute']); //create module
    app.factory("Rest", ['$http', function($http){ //create service factory
        var allUsers = []; //initialize empty allUsersArray
        return{
            getUsers: function(doneCallback){ //getUsers function with a callback parameter
                var getHttp = $http({ //GET request from my test.json
                    method: 'GET',
                    url: 'test.json'
                });
                getHttp.then(function successCallback(response) {
                    var users = response.data;
                    for(var i = 0; i < users.people.length; i++){
                        allUsers.push(users.people[i]); //add the objects to the allUsers array at the top
                    }
                    console.log("This is from within the SERVICE: " + allUsers[1].first); //showing that I can access the allUsers array within the service.
                    doneCallback(response.data.people); //my sad attempt to call this in the controller and still ended up being undefined.
                }, function errorCallback(response) {
                    console.log("Error!");
                });
            }
        }
    }]);
    app.controller('mainCtrl', ['$scope', 'Rest', function($scope, Rest){
        $scope.usersArray = [];
        //when the get request is completed fill in the $scope.usersArray
        $scope.addUsers = function(users){
            for(var i = 0; i < users.length; i++){
                $scope.usersArray.push(users); //trying to add the users from the SERVICE to the CONTROLLER $scope.usersArray[]
            }
            console.log("This is from within the CONTROLLER: " + $scope.usersArray[1].first); //showing up as undefined :(
        }
        Rest.getUsers($scope.addUsers);
        //$scope.getUsers = Rest.getUsers;
    }]);

index.html(没有什么特别的,因为我们在控制台中查找来自我的updateUser.php的正确响应)

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>Restful Test</title>
</head>
<body ng-controller="mainCtrl">
    <h1>Welcome to REST Test!</h1>
</body>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="app.js"></script>
</html>

updateUser.php

<?php 
    $use = json_decode(file_get_contents("php://input"));
    for($i=0; $i < count($use->users); $i++){
        var_dump($use->users[$i]->first . " " . $use->users[$i]->last . " is a " . $use->users[$i]->position);
    }
?>

test.json

{
    "people": [
        {"first": "Edward", "last": "Smith", "age": 18, "position": "Accountant"},
        {"first": "Lucas", "last": "Santos", "age": 23, "position": "Programmer"},
        {"first": "Jeremy", "last": "Grey", "age": 27, "position": "Fire Fighter"}
    ]
}

因此,为了测试和解决这个问题,我尽量保持代码的简单性。

我遇到的问题是,为了操作使用Angular的$http服务GET方法拉入的JSON数据,我首先需要在控制器中访问它,这样我就可以更新它,并在控制器中对它做任何我想做的事情。但现在的问题是$http调用是异步的,在需要在控制器中填充$scope.usersArray之前,它不会获得JSON,因此使其未定义

因此,我尝试制作一个名为doneCallback的回调函数,该函数在$http.then方法中触发,该方法承诺在触发回调函数之前完成。由于某种原因,它不是,而且无论怎样,我试图填充的控制器中的数组仍然是未定义的。

您可以简单地从Rest服务返回承诺,例如

app.factory("Rest", ['$http', function($http) {
    return {
        getUsers: function() {
            return $http.get('test.json').then(function(response) {
                // the return value of this promise chain...
                return response.data.people || [];
            });
        }
    };
}])

和在你的控制器

$scope.usersArray = [];
Rest.getUsers().then(function(people) {
    console.log(people);
    // to push all the new "people" into the array...
    Array.prototype.push.apply($scope.usersArray, people);
});

请参阅"合并两个阵列"