使用Angular捕获所有$ http前提

时间:2013-11-13 20:45:13

标签: http angularjs callback

我想刷新导航栏中使用的用户的状态。但现在我必须在所有.all(function() { refresh() });场所呼叫$http.post

我可以使用配置来捕获所有这些吗?

2 个答案:

答案 0 :(得分:1)

是的,你可以intercept $http using request/response interceptors

但更好的设计可能是在$watch为POST调用的属性上的导航栏设置controller(可能在$rootScope,但不建议这样做)

答案 1 :(得分:0)

这就是我最终做的事情:

app.config(function($httpProvider, $provide) {
  // This sucks but Angular is so compliated that we can't get the rootScope
  // in a simple way inside a factory for a configuration
  function getRootScope() {
    return angular.element('body').scope();
  }

  // Call refresh() after each HTTP destructive action
  $provide.factory('refreshAfterRequests', function($q) {
    return {
      'response': function(response) {
        // Every non-GET request can potentialy change the state of the user
        if (response.config.method !== 'GET') {
          getRootScope().refresh();
        }

        return response;
      }
    };
  });

  // The refresh is an interceptor on all HTTP requests made with Angular
  $httpProvider.interceptors.push('refreshAfterRequests');
});

如果某人有更好的方法,比如如何从拦截器内部获取范围,我很乐意改变这个答案。