toddmotto / ama

Ask me anything!
20 stars 3 forks source link

Angular 1.3.* Event listener for Ajax call #38

Closed timothylombrana closed 8 years ago

timothylombrana commented 8 years ago

Suppose I need to fire a function every time there was an $http request being made. What would be your angular-way of doing this?

toddmotto commented 8 years ago

Hey man. So, what I'd probably have is something like this:

function MyService($http, $rootScope) {
  function doSomething(data) {
    $rootScope.$emit('http:stuffAboutToHappen' [, data ]);
    return $http.get('/url').then(function (response) {
      $rootScope.$emit('http:stuffHappened' [, data ]);
      return response.data;
    };
  }
  return {
    doSomething: doSomething
  };
}

Then listen to $rootScope.$on('http:stuffAboutToHappen', function (event, data) {...}); in your Controller :) hope that helps.

timothylombrana commented 8 years ago

Thanks so much for the quick response, next time your in Austin pints are on me! Could this apply to a catch all request made, so if the request was made from a different view and wanted to emit there has been a request and catch it on a completely different view. I need to invalidate cache, so trying to do a catch all event on all http calls.

toddmotto commented 8 years ago

If you want to capture view events, check out the events ui-router emits, stateChangeStart and success and so on. There's also HTTP Interceptors that you can jump into as well :) pint in Austin sounds awesome man! Loved that place so much.

timothylombrana commented 8 years ago

Cheers! Thanks Todd!

toddmotto commented 8 years ago

:D you're welcome!