Paolo B Paolo B - 1 year ago 80
AngularJS Question

How to populate angular controller variables from an array that is retieved by $http.get

Using Angular 1.5.9 on frontend and WebAPI 2 on server. Calling a standard

$http.get
in the service to
Get()
method on controller. This is returning the ViewModel that I want to populate variables with in angular controller.

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;

};


I am getting error
"Cannot read property 'cars' of undefined"
:

Error Message

As you can see the
console.log
is showing the
model.carList
so I know issue is in controller code populating the other variables. What am I missing here? Any help appeciated.

Edit: 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
};
};

Answer Source

You have to wrap your $scope variable population in a promise approach. Since the model.carList data is not yet loaded when the population is happening, it's normal that the error arrises (Cannot read property 'cars' of undefined; meaning carList is undefined).

In your service carService.getCarsByMake you have to return a promise( $http.get method)

Only when the promise is resolved, you can populate your $scopevariables with this data.

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

};

Return $http request on the service side :

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
    };
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download