无法读取属性然后在角度JS中的未定义错误

时间:2015-07-04 08:27:40

标签: javascript angularjs

这是我的angularJS服务和控制器。

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();

}]);

当控制器加载时,我看到以下错误。

无法读取未定义的属性'then'     at l。$ scope.GetBrands(Controllers.js:337)

请有人帮助我做错了什么?

1 个答案:

答案 0 :(得分:1)

当数据尚未缓存时,您没有在HTTP请求的情况下返回承诺。

正确的代码是:

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;
});

此外,您不需要创建虚拟延迟对象,您可以使用$q.when返回已解决的承诺。