javascript – 用工厂获取数据json

前端之家收集整理的这篇文章主要介绍了javascript – 用工厂获取数据json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试学习如何在工厂内获取数据.目前我正在使用控制器获取数据

factory.js

  1. angular
  2. .module('app')
  3. .factory('Product',['$http',function($http){
  4. return{
  5. get: function(){
  6. return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
  7. return response.data;
  8. });
  9. }
  10. };
  11. }])

细节poduct.js

  1. angular
  2. .module('app')
  3. .controller('productDetailsCtrl',['$scope','$stateParams','Product',function($scope,$stateParams,Product){
  4. $scope.id=$stateParams.id;
  5. Product.get().then(function(data) {
  6. $scope.singleItem = data.filter(function(entry){
  7. return entry.id === $scope.id;
  8. })[0];
  9. });
  10. }]);

产品detail.html

但是当我更改代码以便像这样移动工厂内的fecthing时
 factory.js

  1. return{
  2. get: function(){
  3. return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
  4. return response.data;
  5. });
  6. },find: function(){
  7. return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
  8. var singleItem = data.filter(function(entry){
  9. return entry.id === id;
  10. })[0];
  11. });
  12. }
  13. };

细节product.js

  1. angular
  2. .module('app')
  3. .controller('productDetailsCtrl',Product){
  4. Product.find($stateParams.product,function(singleItem){
  5. $scope.singleItem = singleItem;
  6. });
  7. }]);

它给我一个错误,数据没有定义.

最佳答案
您忘记从find方法承诺返回singleItem.然后放置.then承诺从中获取数据.

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

调节器

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

猜你在找的JavaScript相关文章