1

I've added the following to my app.config in order to resolve a globally needed variable before allowing any of my routes to kick off their associated controller. This has been working great, however I am concerned about scenarios in which this async call falls. If that were to happen this would not resolve properly and my app would never render. How could I protect against this scenario?

var originalWhen = $routeProvider.when;

$routeProvider.when = function(path, route) {
  if (!route.resolve) {
    route.resolve = {};
  }
  angular.extend(route.resolve, {
    availableCodes: function($rootScope, serverService) {
      if ($rootScope.isAuthenticated) {
        return numbersService.getAvailableCodes().$promise.then(function(data) {
          $rootScope.availableCodes = data.codes;
        });
      }
    }
  });
  return originalWhen.call($routeProvider, path, route);
};
1
  • Do you have some default codes you can fall back on? If so, you can add a catch to your Promise chain and assign $rootScope.availableCodes to a default value. Commented Mar 10, 2016 at 21:19

1 Answer 1

0

For global resolvers patching when isn't the best solution (method patching is an extreme case and should be avoided if possible), generally putting them to $routeChangeStart listener is cleaner and gives more control.

The errors should be handled in $routeChangeError, listeners get rejection reason as the fourth argument:

  var ignored = ['/resolver-error'];

  $rootScope.$on('$routeChangeStart', function (e, to) {
    if (ignored.indexOf(to.originalPath) >= 0)
      return;

    to.resolve = to.resolve || {};
    // can be overridden by route definition
    to.resolve.availableCodes = to.resolve.availableCodes || 'availableCodesService';
  });

  $rootScope.$on('$routeChangeError', function (e, to, from, reason) {
    if (reason === ...) {
      $location.path('/resolver-error');
    }
  });

This allows to skip this resolver on at least one route which is supposed to provide a feedback on resolution error.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.