Devesh Agrawal
Devesh Agrawal

Reputation: 9212

Can not read property then of undefined error in angular JS

This is my angularJS service and controller.

sampleApp.factory('BrandService', function($http, $q) {

    var BrandService =  {};
    var BrandList = [];

    BrandService.GetBrands = function() {
        var Info = {};
        Info.Action = "GET";
        Info = JSON.stringify (Info);

        var req = {
            url: BrandURL,
            method: 'POST',
            headers: { 'Content-Type': 'application/json'},
            data: Info
        };  
        if ( BrandList.length == 0 )
        {
            $http(req)
            .success(function(response) {
                BrandList = response.data
                alert ('Brand Fetching is successful');
                return response.data;
            })  
            .error(function (data, status, headers, config) {
                alert ('Brand Fetching Error');
                alert (status);
                alert (data);
            });
        }
        else
        {
           var deferred = $q.defer();
           deferred.resolve(BrandList);
           return deferred.promise;
        }
    }

    return BrandService;
});


sampleApp.controller('BrandController', ['$scope', 'BrandService', function ($scope, BrandService){

    $scope.Brands = [];

    $scope.GetBrands = function() {
        BrandService.GetBrands().then(function(data) {
            $scope.Brands = data;
        });
    };

    $scope.GetBrands();

}]);

When controller is loading I m seeing the following error.

Cannot read property 'then' of undefined at l.$scope.GetBrands (Controllers.js:337)

Can please someone help me what i m doing wrong?

Upvotes: 1

Views: 97

Answers (1)

dfsq
dfsq

Reputation: 193261

You are not returning promise in case of HTTP request when data is not yet cached.

Correct code would be:

sampleApp.factory('BrandService', function($http, $q) {

    var BrandService = {};
    var BrandList = [];

    BrandService.GetBrands = function() {

        var req = {
            url: BrandURL,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            data: JSON.stringify({Action: 'GET'})
        };

        if (BrandList.length) {
            return $q.when(BrandList);
        }

        return $http(req)
            .success(function(response) {
                BrandList = response.data
                alert('Brand Fetching is successful');
                return response.data;
            })
            .error(function(data, status, headers, config) {
                alert('Brand Fetching Error');
                alert(status);
                alert(data);
            });
    }

    return BrandService;
});

Also you don't need to create dummy deferred object, you can return resolved promise with $q.when.

Upvotes: 1

Related Questions