Search code examples
angularjsangularjs-routing

Execute function before routeprovider starts executing resolve list


I'm working on an Angular project that works with server cache. My plan is:

  1. Create a service (CacheService) that asks server about cache status and stores this info into localStorage.
  2. So then other services that are called in routeProvider resolve object can ask CacheService about their cache status and, if it's outdated, call to server to get new data or, if cache has not changed, use their locally cached data

So the question is: ¿is there any way to execute a async function before resolvers are executed? Or ¿is there any way in resolvers to wait to other resolvers before execute?

Thanks in advance


Solution

  • The $route service provides a $routeChangeStart event that you can use to accomplish this.

    Broadcasted before a route change. At this point the route services starts resolving all of the dependencies needed for the route change to occur. Typically this involves fetching the view template as well as any dependencies defined in resolve route property. Once all of the dependencies are resolved $routeChangeSuccess is fired.

    The route change (and the $location change that triggered it) can be prevented by calling preventDefault method of the event. See $rootScope.Scope for more details about event object.

    You should be able to use this event to hop into the route flow, perform your cache check, then make a decision what to do next (use cache, abort route, etc.)