如何从 $http.get 检索到的数组填充 Angular 控制器变量

How to populate Angular controller variables from an array that is retrieved by $http.get

在前端使用 Angular 1.5.9,在服务器上使用 WebAPI 2。在服务中调用标准 $http.get 到控制器上的 Get() 方法。这将返回我想在 angular 控制器中填充变量的 ViewModel。

var carListController = function ($http, $scope, carService) {

    var model = this;

    model.carList = carService.getCarsByMake('Bentley', 10);

    console.log(model.carList);

    model.cars = model.carList[0].cars;

    model.totalCars = model.carList[0].totalCars;

    model.numberOfPages = model.carList[0].numberOfPages;

};

我收到这个错误:

Cannot read property 'cars' of undefined

如您所见,console.log 显示的是 model.carList,所以我知道问题出在填充其他变量的控制器代码中。我在这里错过了什么?欢迎任何帮助。

编辑: carService

var cars = [];

var carService = function ($http) {

    var getCarsByMake = function (make, size) {

        $http.get('http://localhost:50604/api/cars?make=' + make + '&size=' + size)
            .then(function (response) {
                // Success
                angular.copy(response.data, cars);
            }, function () {
                // Failure
            });

        return cars;
    };

    return {
        getCarsByMake: getCarsByMake
    };
};

您必须将您的 $scope 可变总体包装在承诺方法中。 由于填充时model.carList数据还没有加载,所以出现错误是正常的(Cannot read 属性 'cars' of undefined; meaning carList is undefined)。

在您的服务中 carService.getCarsByMake 您必须 return 一个 promise$http.get 方法)

只有当承诺得到解决时,您才能使用此数据填充您的$scope变量。

var carListController = function ($http, $scope, carService) {    
    var model = this;    
    carService.getCarsByMake('Bentley', 10).then(function(response){
        model.carList = response.data;
        model.cars = model.carList.cars;
        model.totalCars = model.carList.totalCars;
        model.numberOfPages = model.carList.numberOfPages;
    });    

};

Return $http服务端请求:

var cars = [];
var carService = function ($http) {
    var getCarsByMake = function (make, size) {
        return $http.get('http://localhost:50604/api/cars?make=' + make + '&size=' + size);
    };

    return {
        getCarsByMake: getCarsByMake
    };
};