在我的角度应用程序中,我想覆盖$ http。所以只要有$ http服务调用,它会在原始数据中附加一些默认数据并发送请求。同样,当一个响应到来时,它会检查一些特定的数据并重新格式化它,success()将得到修改后的响应。
我是Angularjs的新手。谁可以帮我这个事?
预先感谢您。
在我的角度应用程序中,我想覆盖$ http。所以只要有$ http服务调用,它会在原始数据中附加一些默认数据并发送请求。同样,当一个响应到来时,它会检查一些特定的数据并重新格式化它,success()将得到修改后的响应。
我是Angularjs的新手。谁可以帮我这个事?
预先感谢您。
您可以使用下面的代码。
//或者,通过匿名工厂注册拦截
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
return {
'request': function(config) {
// do your stuff
return config;
},
'response': function(response) {
// do your stuff
return response;
}
};
});
你必须探索通过角度实现的$ http方法。你可以看到一个功能
function sendReq (config, reqData, reqHeaders)
在这里,你可以改变reqData按您的要求。 现在类似的成功和完成功能,你可以使用你的代码来处理数据,然后发送到回调。 否则,您也可以更改来自xhr请求的数据。 这个你会从函数createxhr()中得到的角度
看看$ http拦截器(https://docs.angularjs.org/api/ng/service/ $ http)。使用它们,您可以拦截请求和ajax请求的响应。
创建类似的服务:
module.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'request': function(config) {
// do something pre-request, like inject Headers properties:
//config.headers['Authorization'] = '';
return config;
},
'requestError': function(rejection) {
//do something with the error
return $q.reject(rejection);
},
'response': function(response) {
// do something on success of request
return response;
},
'responseError': function(rejection) {
// do something on error like:
//if(response.status == 401){
// userUnauthorized();
//}
return $q.reject(rejection);
}
};
});
在你的应用程序配置,推动拦截器:
module.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);
它看起来不错。让我试试看。谢谢!! – Alp
可以使用的$ HTTP拦截。阅读关于这里“http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/” –
你到目前为止尝试过什么?任何支持面向方面构造的库都可以工作。你可以看看这个:https://github.com/mgechev/angular-aop –