gpt4 book ai didi

javascript - 使用工厂获取数据 json

转载 作者:搜寻专家 更新时间:2023-11-01 04:22:44 25 4
gpt4 key购买 nike

我正在尝试学习如何在工厂内获取数据。目前我正在使用 Controller 获取数据

工厂.js

angular
.module('app')
.factory('Product', ['$http', function($http){
return{
get: function(){
return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
return response.data;
});
}
};
}])

细节产品.js

    angular
.module('app')
.controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
$scope.id=$stateParams.id;
Product.get().then(function(data) {
$scope.singleItem = data.filter(function(entry){
return entry.id === $scope.id;
})[0];
});
}]);

产品详情.html

<a href="{{singleItem.url}}">
<p>{{singleItem.id}}</p>
<p>{{singleItem.name}}</p>
<img src="{{singleItem.image}}" alt="{{singleItem.name}}">
</a>

但是当我更改代码以像这样将 fecthing 移动到工厂内部时 工厂.js

return{
get: function(){
return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
return response.data;
});
},
find: function(){
return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
var singleItem = data.filter(function(entry){
return entry.id === id;
})[0];
});
}
};

细节产品.js

angular
.module('app')
.controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
Product.find($stateParams.product,function(singleItem){
$scope.singleItem = singleItem;
});
}]);

它给我一个数据未定义的错误。

最佳答案

您忘记从 find 方法 promise 中返回 singleItem。然后将 .then 放在 promise 上以从中获取数据。

find: function(id){
return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
var singleItem = response.data.filter(function(entry){
return entry.id === id;
})[0];
return singleItem;
});
}

Controller

Product.find($stateParams.id).then(function(singleItem){
$scope.singleItem = singleItem;
});

关于javascript - 使用工厂获取数据 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41250482/

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