JavaScript 在服务中处理$ http响应

我最近公布的我面对这个问题的详细说明,这里的SO。由于我无法发送实际的$http请求,因此我使用了超时来模拟异步行为。在@Gloopy的帮助下,从模型到视图的数据绑定工作正常

现在,当我使用$http而不是$timeout(在本地测试)时,我可以看到异步请求成功,并且data在我的服务中充满了json响应。但是,我的看法没有更新。

回答:

这个想法是您直接使用promise及其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;

});

};

});

以上是 JavaScript 在服务中处理$ http响应 的全部内容, 来源链接: utcz.com/qa/423585.html

回到顶部