Angularjs 中的 jQuery ajax beforeSend 相当于什么? [英] What is the equivalent of jQuery ajax beforeSend in Angularjs?
问题描述
我熟悉 Jquery AJAX 调用,它具有不同的回调,如 beforeSend、success、complete 等.
I am familiar with Jquery AJAX call, which has different callbacks like beforeSend, success, complete, etc.
这是使用 Jquery 的 AJAX 调用示例:
This is the example AJAX call with Jquery:
$.ajax({
url: 'register.php',
type: 'POST',
data: {name:name, email:email},
beforeSend: function() {
// show loading GIF
},
complete: function() {
// hide loading GIF
},
success: function(data) {
// parse response
}
});
我想使用 AngularJS 实现同样的效果.
I want to achieve the same using AngularJS.
对于 AngularJS AJAX 请求,是否有像 beforeSend 这样的回调?到目前为止,这是我的代码,但我不确定在哪里可以在我的代码中使用像 beforeSend 这样的回调(以便我可以显示正在加载的 GIF 图像):
Is there a callback like beforeSend for AngularJS AJAX request ? This is my code so far, but i am not sure where can i use a callback like beforeSend (so that i can display a loading GIF image) in my code:
$http.post('register.php', {'name': $scope.name, 'email': $scope.email})
.success(function(data, status, headers, config) {
if (data != '') {
}
});
推荐答案
默认情况下,Angular 不提供 beforeSend 和 complete,但您可以使用拦截器来实现它们.这是我的实现:
By default Angular does not provide beforeSend and complete but you can implement them by using interceptors. Here is my implementation:
(function() {
var app = angular.module("app");
app.factory("interceptors", [function() {
return {
// if beforeSend is defined call it
'request': function(request) {
if (request.beforeSend)
request.beforeSend();
return request;
},
// if complete is defined call it
'response': function(response) {
if (response.config.complete)
response.config.complete(response);
return response;
}
};
}]);
})();
然后你必须像这样注册你的拦截器:
Then you have to register your interceptor like this:
(function () {
var app = angular.module('app', ['ngRoute']);
app.config(["$routeProvider", "$httpProvider", function ($router, $httpProvider) {
// Register interceptors service
$httpProvider.interceptors.push('interceptors');
$router.when("/", { templateUrl: "views/index.html" })
.otherwise({ redirectTo: "/" });
}]);
})();
在这段代码之后,你可以像这样使用它:
After this code you can use it like this:
var promise = $http({
method: 'POST',
url: constants.server + '/emails/send',
data: model,
beforeSend: function() {
model.waiting = true;
},
complete: function() {
model.waiting = false;
}
});
这篇关于Angularjs 中的 jQuery ajax beforeSend 相当于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!