如何等待响应来自$http
请求," angularjs"?
在ajax
中,一个成功的方法是设置async = false
,就像这样,
jQuery.ajax({
url: '/Something/Index',
success: function (result) {
result;
},
async: false
});
但是它没有在angularjs.的$ http请求中工作。我有什么方法吗?
答案 0 :(得分:0)
$http.get("url")
.then(response => {
// async success callback
})
.catch(err => {
// async error callback
});
答案 1 :(得分:0)
您可以使用AngularJS中$http
服务返回的承诺,并使用.then
函数。这可以确保收到第一个函数响应,然后只执行.then
函数内的代码。
示例代码如下:
var app = angular.module("app", []);
app.factory('myService', function ($http) {
return {
serverCall: function () {
return $http.get('/Something/Index').then(function (response) {
console.log(response);
return response;
});
}
};
});
app.controller("myController", function ($scope, myService) {
$scope.GetDataFromServer = function () {
// make the ajax call
var myData = myService.serverCall();
// this executes after that ajax call is completed
myData.then(function (result) {
$scope.data = result;
});
};
});