gpt4 book ai didi

javascript - 无法读取 Angular JS 中未定义错误的属性

转载 作者:行者123 更新时间:2023-11-28 00:07:26 24 4
gpt4 key购买 nike

这是我的 angularJS 服务和 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();

}]);

当 Controller 加载时,我看到以下错误。

无法读取未定义的属性“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com