[英]Catch an error anywhere angularjs
I'm working on an Angularjs app that frequently communicates with a server. 我正在开发一个经常与服务器通信的Angularjs应用程序。 I've been tasked with implementing security, when there wasn't any before.
我以前从未有过实施安全性的任务。
This means that I've changed all the server side api calls to return a 403-unauthorized http status code when the user attempts to perform an action they aren't allowed to perform. 这意味着,当用户尝试执行不允许执行的操作时,我已经更改了所有服务器端api调用,以返回403未经授权的http状态代码。
Now, I COULD go and hunt down every single API call that the app makes to the server, and call a function that handles the same error the same way in each one. 现在,我可以查找该应用程序对服务器进行的每个API调用,并调用一个函数,每个函数以相同的方式处理相同的错误。 But I would rather find some way to say "Any time this page gets a 403-unauthorized response, do this function."
但是,我宁愿找到某种方式说“只要该页面收到403未经授权的回复,就执行此功能”。 Is what I'm asking possible?
我要问的可能吗?
You can use $http
interceptors. 您可以使用
$http
拦截器。 By adding an interceptor, you will be able to intercept the response to check the status code and do whatever you want before the original requiring gets notified. 通过添加拦截器,您将能够拦截响应以检查状态代码,并在通知原始要求之前做您想做的任何事情。
Angularjs $http docs AngularJS $ http文档
For example: 例如:
app.config(function ($httpProvider) {
// it can be added by a explicit factory declaration
// angular.module(...).factory('myHttpInterceptor', function ...
$httpProvider.interceptors.push(function($q, $state) {
return {
'request': function(config) {
return config;
},
'response': function(response) {
if(response.statusCode === 403){
$state.go('my.unauthorized.state');
// or maybe
// $rootScope.$broadcast('unauthorized');
}
return response;
}
};
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.