angularjsasp.net-web-apiangular-controller

How to populate Angular controller variables from an array that is retrieved 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 get this 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
    };
};

Solution

  • 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.cars;
            model.totalCars = model.carList.totalCars;
            model.numberOfPages = model.carList.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
        };
    };