每当有$ http请求时,以及接收到响应后,是否有办法监听/绑定事件?

实际上,我是通过提供自己的事件和侦听器来手动完成此操作的,但是我只是好奇Angular JS中是否已经有侦听器了?

我之所以想这样做,是因为我的应用程序每次发送/执行$ http请求时,都希望显示加载屏幕以指示该应用程序正在检索数据,然后在收到响应后将其隐藏。

谢谢!

最佳答案

您可以使用interceptor来执行此操作

var httpinterceptor = function ($q, $location) {
    return {
        request: function (config) {
            //show your loading message
            console.log(config);
            return config;
        },

        response: function (result) {
            //hide your loading message
            console.log('Repos:', result);
            return result;
        },

        responseError: function (rejection) {
            //hide your loading message
            console.log('Failed with', rejection);
            return $q.reject(rejection);
        }
    }
};

app.config(function ($httpProvider) {
    $httpProvider.interceptors.push(httpinterceptor);
});


演示:Fiddle

09-25 17:31
查看更多