Angularjs Post-Receive Hook 还是类似的?

标签 angularjs

有没有办法在每次从服务器返回响应后调用函数而不在回调中显式调用它?

主要目的是我确实有一个通用的错误处理程序服务,我在每个请求的回调中调用它,我想在某个地方指定它,它应该被自动调用。

最佳答案

我给 Gloopy 一个 +1 的解决方案,但是,other post他引用了在配置和拦截器中定义的函数中进行 DOM 操作。相反,我将启动微调器的逻辑移到了拦截器的顶部,并在 $rootScope 中使用了一个变量。控制微调器的隐藏/显示。它似乎工作得很好,我相信它更具可测试性。

<img ng-show="polling" src="images/ajax-loader.gif">

angular.module('myApp.services', ['ngResource']).
.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
    var spinnerFunction = function (data, headersGetter) {
        return data;
    };
    $httpProvider.defaults.transformRequest.push(spinnerFunction);
})
//register the interceptor as a service, intercepts ALL angular ajax http calls
.factory('myHttpInterceptor', function ($q, $window, $rootScope) {
    return function (promise) {
        $rootScope.polling = true;
        return promise.then(function (response) {
            $rootScope.polling = false;
            return response;
        }, function (response) {
            $rootScope.polling = false;
            $rootScope.network_error = true;
            return $q.reject(response);
        });
    };
})
// other code left out

关于Angularjs Post-Receive Hook 还是类似的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11863148/

相关文章:

javascript - 在 Angularjs 中访问模板内的属性值

javascript - angularjs 脚本不工作

javascript - AngularJS Jasmine 单元测试

angularjs - 用于大型项目的 Angular 2 或 NodeJs/Express

angularjs - 如何在 Angular View 中使用 ASP.Net MVC View .cshtml 而不是 .html

javascript - ES6 中的 AngularJs 提供程序

html - 动态更改表格背景angularjs

css - 在 AngularJS 指令中调整 div 的大小?

arrays - AngularJS 删除空值

angularjs - 追踪无限摘要错误