2015-07-04 37 views
1

这是我的angularJS服务和控制器。无法读取属性,然后在角度JS中未定义的错误

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

}]); 

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

不能在我读出属性“然后”未定义 的$ scope.GetBrands(Controllers.js:337)。

可以请人帮我,我在做错了吗?

回答

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返回解决的承诺。

相关问题