我正在尝试学习如何在工厂内获取数据.目前我正在使用控制器获取数据
factory.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;
});
}
};
}])
细节poduct.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];
});
}]);
产品detail.html
但是当我更改代码以便像这样移动工厂内的fecthing时
factory.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];
});
}
};
细节product.js
angular
.module('app')
.controller('productDetailsCtrl',Product){
Product.find($stateParams.product,function(singleItem){
$scope.singleItem = singleItem;
});
}]);
它给我一个错误,数据没有定义.
最佳答案
您忘记从find方法承诺返回singleItem.然后放置.then承诺从中获取数据.
原文链接:https://www.f2er.com/js/429117.htmlfind: 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;
});
}
调节器
Product.find($stateParams.id).then(function(singleItem){
$scope.singleItem = singleItem;
});