微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angularjs后接收钩或类似?

有没有办法在从服务器返回响应后每次都调用一个函数,而不是在回调之后显式调用它?

主要目的是我有一个通用的错误处理程序服务,我在每个请求的回调函数调用,我想在某处指定它,它将被自动调用.

我给了Gloopy一个解决方案,但是,他引用的 other post在DOM和拦截器定义的函数中进行DOM操作.相反,我将启动微调器的逻辑移到了inter the的顶部,我在$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

原文地址:https://www.jb51.cc/angularjs/140733.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐