如果 $http 调用出错,我只有一种方法可以向用户显示,目前我通过执行以下操作来调用它:
$http({
//do stuff
}).
error(function(){
$scope.$broadcast('error');
});
我有一个指令,用 $on 监听错误。
然而,我只是在每次使用 $http 时都重复 $broadcast,是否可以扩展默认错误回调以每次都广播错误?
最佳答案
我建议您改用响应拦截器。
您可以在 AngularJS API Reference 上找到详细信息,但这就是它的工作方式:
angular.module('app', []);
angular.module('app').factory('myHttpErrorInterceptor', function ($q) {
return {
'responseError': function (rejection) {
console.log('DEBUG: Status:', rejection.status);
return $q.reject(rejection);
}
};
});
angular.module('app').config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpErrorInterceptor');
});
angular.module('app').run(function ($http) {
$http.get('http://example.org/that-doesnt-exist');
});
代替我的 console.log
,您可以广播您的错误。
你可以找到一个活生生的例子here .
关于javascript - 在 Angular 中广播站点范围的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22275153/