gpt4 book ai didi

javascript - AngularJS 中的工厂 "is not defined"

转载 作者:行者123 更新时间:2023-12-03 06:08:49 25 4
gpt4 key购买 nike

我是 Angular 世界的初学者,我不明白为什么我仍然收到“未定义”错误。这是我的代码:

angular.module('dopasujApp').factory('getProducts', ['$http', function ($http) {
var dataFactory = {};
dataFactory.sort='ASC';
dataFactory.orderBy='PRODUCT_NAME';
dataFactory.search='a';
dataFactory.filters={};
dataFactory.filters.ATTRIBS=[46,25];
dataFactory.filters.SIZE=[165,40];

getProducts.listProducts = function() {
var request = $http({
method: "POST",
url: "http://******/backend/internalAPI.php?action=getListing&fit=1&limit=10&vendor=20",
headers: {
'Content-Type': 'application/json'
},
data: {
data: dataFactory
}
});

var products = angular.fromJson(request);

return products;
}

return false;

}]);

这是我的 Controller (现在仅用于测试目的)。

angular.module('dopasujApp')
.controller('MainCtrl', ['getProducts', '$scope','$rootScope',
function (getProducts, $scope,$rootScope) {
console.log(getProducts.listProducts())
}
]);

最佳答案

  1. 工厂中的 getProducts 变量未定义。您之前使用的名称只是 Angular 的信息性名称

  2. 在您的工厂中,您返回“false”作为实际结果。因此, Angular 将您的“错误”视为结果。

它应该看起来像这样:

angular.module('dopasujApp').factory('getProducts', ['$http', function ($http) {
var dataFactory = {}, getProducts = {};
dataFactory.sort='ASC';
dataFactory.orderBy='PRODUCT_NAME';
dataFactory.search='a';
dataFactory.filters={};
dataFactory.filters.ATTRIBS=[46,25];
dataFactory.filters.SIZE=[165,40];

getProducts.listProducts = function() {
return $http({
method: "POST",
url: "http://******/backend/internalAPI.php?action=getListing&fit=1&limit=10&vendor=20",
headers: {
'Content-Type': 'application/json'
},
data: {
data: dataFactory
}
});
}

return getProducts;

}]);

Controller

angular.module('dopasujApp').controller('MainCtrl', ['getProducts', '$scope','$rootScope', 
function (getProducts, $scope,$rootScope) {
getProducts.listProducts().then(function(res) {
console.log(res.data);
});
}
]);

编辑:

另请注意,$http 返回 promise ,但不是实际的查询结果,相应更新了我的示例

关于javascript - AngularJS 中的工厂 "is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39411104/

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