2015-05-08 76 views
0

我有我的父母和孩子控制器中的HTTP请求:如何制作多个http请求?

父控制器

//Product is a $resource object that return http request as a promise. 
Product.getItem() 
    .then(function(items) { 
     $scope.items = items 
     //do something in the parent controller. 
}) 

儿童控制器

Product.getItem() 
    .then(function(items) {   
     $scope.items = items 
     //do something in the child controller 
}) 

制品厂

angular.module('testApp').factory('Product', function($http,$q) { 
    var service = {} 
    service.getItem = function() { 
     return http.$get('api/url'); 
    } 
    return service; 
}) 

子控制器在我处于特定页面时启动。问题是当我启动这些页面时,代码会对api/url进行双http请求,因为父控制器和子控制器都发出请求。虽然我的应用程序仍然有效,但我想知道是否有更好的解决方法。谢谢您的帮助!

+0

你能对$ scope.items做一些验证吗? if(!$ scope.items){Product.getItem()...} – tpie

+0

否,因为当通过http请求加载页面时,$ scope.items始终未定义。 – FlyingCat

+0

如果**子控制器**确实是**父控制器**的孩子,那么它将继承父范围,从而继承'$ scope.items'。 – Phil

回答

1

编辑: 我调查了菲尔的评论了一下,并修正了(改写了)我的例子。最底层的掠夺者反映了这些变化。以下是更新后的代码:

app.controller('MainCtrl', function($scope, getStore) { 
    getStore.get().then(function(data) { 
    $scope.data = data 
    }) 
}); 
app.controller('ChildCtrl', function($scope, $timeout, getStore) { 
    $timeout(function() { 
    getStore.get().then(function(data) { 
     $scope.test = data 
    }) 
    },3000) 

}); 

app.factory('getStore', function($http, $q) { 
    var self = this; 
    var data; 
    return { 
    get: function() { 
     if (data) { 
     console.log(data); 
     console.log('already got data') 
     return $q.when(data) 
     } else { 
     data = $http.get('test.json') 
     .then(function(response) { 
      console.log('fetched data') 
      return response.data; 
     }) 
     return data 
     } 
    } 
    } 
}) 

这里是一个解决方案 - 分开你的$ http.get到工厂和存储的价值在那里。工厂是单身人士,所以两个控制器都可以访问和检查数据。

JS:

app.controller('MainCtrl', function($scope, getStore) { 
    $scope.data = getStore.get() 
}); 
app.controller('ChildCtrl', function($scope, $timeout, getStore) { 
    $timeout(function() { 
    $scope.data = getStore.get() 
    var check = getStore.checkData(); 
    console.log('Data in store: ' + angular.toJson(check)); 

    },1000) 
    $scope.getData = function() { 
    console.log(getStore.get()); 
    } 
}); 

app.factory('getStore', function($http) { 
    var self = this; 
    return { 
    data: undefined, 
    get: function() { 
     if (self.data) { 
     console.log('already got data') 
     return self.data 
     } else { 
     $http.get('test.json') 
     .success(function(data) { 
      console.log('no data found'); 
      self.data = data; 
      console.log(self.data); 
      return self.data; 
     }) 
     } 
    } 
    } 
}) 

它只是运行检查,以查看该值是否已经存储或没有,然后返回它,如果它是的,如果不是,它得到,商店,并将其返回。

Plunker

+0

里面我看到你的观点。如果所有处理返回数据的逻辑都在子控制器中,则您的代码可以工作。如果我需要在Main Ctrl中对返回的数据做些什么呢?感谢和+1 – FlyingCat

+0

你能说一下吗? – tpie

+0

例如,app.controller('MainCtrl',函数($ scope,getStore){ $ scope.data = getStore.get() 我需要做些事情$ scope.data});在你的主要ctrl – FlyingCat