我最近发布了关于我在 SO面临的问题的详细描述。由于无法发送实际$http请求,我使用超时来模拟异步行为。在@Gloopy 的帮助下,从我的模型到视图的数据绑定工作正常
$http
现在,当我使用$http而不是$timeout(在本地测试)时,我可以看到异步请求成功并且data在我的服务中填充了 json 响应。但是,我的观点没有更新。
$timeout
data
在这里更新了 Plunkr
这是一个可以满足您要求的 Plunk:http ://plnkr.co/edit/TTlbSv?p=preview
这个想法是您直接使用 Promise 及其“then”函数来操作和访问异步返回的响应。
app.factory('myService', function($http) { var myService = { async: function() { // $http returns a promise, which has a then function, which also returns a promise var promise = $http.get('test.json').then(function (response) { // The then function here is an opportunity to modify the response console.log(response); // The return value gets picked up by the then in the controller. return response.data; }); // Return the promise to the controller return promise; } }; return myService; }); app.controller('MainCtrl', function( myService,$scope) { // Call the async method and then do stuff with what is returned inside our own then function myService.async().then(function(d) { $scope.data = d; }); });
这是一个稍微复杂一点的版本,它缓存了请求,所以你只能第一次做(http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview):
app.factory('myService', function($http) { var promise; var myService = { async: function() { if ( !promise ) { // $http returns a promise, which has a then function, which also returns a promise promise = $http.get('test.json').then(function (response) { // The then function here is an opportunity to modify the response console.log(response); // The return value gets picked up by the then in the controller. return response.data; }); } // Return the promise to the controller return promise; } }; return myService; }); app.controller('MainCtrl', function( myService,$scope) { $scope.clearData = function() { $scope.data = {}; }; $scope.getData = function() { // Call the async method and then do stuff with what is returned inside our own then function myService.async().then(function(d) { $scope.data = d; }); }; });