这是我的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”
    在l。$ scope.GetBrands(Controllers.js:337)

可以请人帮我做错什么吗?

最佳答案

如果尚未缓存数据,则在HTTP请求的情况下您不会返回promise。

正确的代码是:

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返回已解决的Promise。

关于javascript - 无法读取 Angular JS中的未定义错误的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31218619/

10-12 15:29