Angularjs后接收钩或类似? [英] Angularjs Post-Receive Hook or Similar?

查看:122
本文介绍了Angularjs后接收钩或类似?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法来调用响应之后,每次都是从服务器返回的功能,但没有明确的回调后调用它?

Is there a way to call a function every time after a response is returned from a server without explicitly calling it after in the callback?

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

The main purpose is that I do have a generic error handler service that I call in every request's callback and I want to specify it somewhere and it shall be called automatically.

推荐答案

我给Gloopy的解决方案+1,但是,其他帖子他引用做DOM操作在配置和拦截器定义的功能。相反,我感动启动微调进入截击顶部的逻辑和我在rootscope控制微调的隐藏/显示使用一个变量。它似乎工作pretty很好,我相信是更测试。

I gave Gloopy a +1 on solution, however, that other post he references does DOM manipulation in the function defined in the config and the interceptor. Instead, i moved the logic for starting spinner into the top of the intercepter and I use a variable in the rootscope to control the hide/show of the spinner. It seems to work pretty well and I believe is much more testable.

<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后接收钩或类似?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆