首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angularjs后接收钩子或类似?

Angularjs后接收钩子或类似?
EN

Stack Overflow用户
提问于 2012-08-08 19:03:33
回答 2查看 6.2K关注 0票数 9

有没有一种方法可以在每次从服务器返回响应后调用函数,而不是在回调中显式调用它?

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-09 02:32:33

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

代码语言:javascript
复制
<img ng-show="polling" src="images/ajax-loader.gif">
代码语言:javascript
复制
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
票数 16
EN

Stack Overflow用户

发布于 2012-08-09 00:50:54

如果您指的是使用$http$resource的请求,则可以通过向$httpProvider.responseInterceptors添加代码来向响应添加通用错误处理。在this post中可以看到更多。

虽然这是关于使用this fiddle启动/停止微调器,但您可以使用// do something on error将代码添加到“停止微调器”部分。感谢来自the groups的zdam!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11863148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档