在 AngularJS 中,如何对“$http”的所有响应应用检查函数
In AngularJS, how can I apply a check function on all the responses of `$http`?
$http({
method: 'POST',
url: '/getAllUsers'
}).success(function(data, status, headers, config) {
if (data.length === 0) {
$location.path('/admin/login');
}
// process data
if (data.ok == 1) {
// correct data
} else {
// error
}
})
我使用 $http
来获取服务器数据,如果身份验证失败,服务器将响应一个空字符串。我想做的是,如果data
为空,那么应用程序应该重定向到登录页面。但是由于有很多控制器,并且每个控制器都有多个$http
调用,所以我不想到处复制和粘贴定向代码。
有什么方法可以在每个$http
响应上"注入"此函数,而无需在任何地方编写相同的代码?
我是否只能在某些特定控制器中的$http
调用上应用它?
您可以使用 http 中间器。在收到来自后端的响应后,立即调用$http交互器的响应方法。您可以修改响应或执行其他操作。该方法使用 http 响应对象调用,需要直接返回响应对象,或者作为包含响应或新响应对象的承诺返回。
$provide.factory('myHttpInterceptor', function() {
return {
'response': function(response) {
if (/* response failed */ ) {
// $rootScope broadcast
// or $location login
// or whatever you want
}
return response;
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
编辑:我不确定这是否是$http
配置的正确用法(我从来没有这样做过..),但您也可以有条件地将transformResponse
函数添加到单个$http
调用中,如下所示:
function transformErrorResponse(data, headersGetter, status) {
if (/* failed */)
// handle failure
}
$http({ transformResponse : transformErrorResponse})
.get(/* */)
.then(/* */);
您可以创建一个factory
定义并将其作为Interceptor
推送到config phase
中(使用 $httpprovider
)
工厂定义
angular.module('myApp').factory('httpInterceptor', ['$location', function($location) {
var httpInterceptor = {
response: function(config){
if (config.data.trim() == "") {
$location.path(''login');
}
return config;
}
};
return httpInterceptor;
}]);
配置阶段
angular.module('myApp').config(['$httpProvider' ,function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}]);
您可以在
模块配置中为$http编写一个简单的配置,并在$http配置的 transformResponse 属性中编写错误处理。像这样:
angular.module("yourModule", []).config ($http) ->
$http({
transformResponse:(data, headersGetter, status)->
/**Handle your data empty stuff here. ***/
})
相关文章:
- 存储$http如何从$http函数(Angularjs)外部获取可访问变量中的响应
- 仅在响应视图中激发jQuery函数
- 使用来自不同异步函数的响应创建一个json对象
- 如何执行ajax响应返回的javascript函数
- php函数的XMLHttpRequest响应不包含任何数据
- 获取javascript函数中另一个javascript函数的响应
- 如何发送作为节点请求响应函数中的代码块的响应
- jquery返回ajax响应和用户定义的变量到函数
- 使用命名函数设置多个事件响应
- 如何等待javascript函数响应
- $http.post() angularjs 响应函数未按正确的顺序执行
- 未调用主干解析ajax响应函数
- AngularJS HTTP 资源 - 响应函数未定义
- 如何将 Rails 变量传递给 AJAX 响应函数
- 我无法让我的按钮响应函数
- 使用Cheerio和Response for Node web scraper,将响应函数结果传递给视图
- 在主页中创建按钮以重定向到响应函数
- 转换node.js HTTP响应函数(使用"request"库)来使用流
- Raphael.js弃用函数和响应函数的替代方案
- Angular 1.5 Scope变量在PouchDB响应函数中不起作用