Here is a Plunk that does what you want: http://plnkr.co/edit/TTlbSv?p=preview
(这是一个可以满足您需求的Plunk: http ://plnkr.co/edit/TTlbSv?p = preview)
The idea is that you work with promises directly and their "then" functions to manipulate and access the asynchronously returned responses.
(这个想法是你直接使用promises和他们的“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;
});
});
Here is a slightly more complicated version that caches the request so you only make it first time ( http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview ):
(这是一个稍微复杂的版本,可以缓存请求,因此您只能第一次创建它( 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;
});
};
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…