2

I'd like to add Angular resolve dynamically after it was defined by the app. Imagine, my app is defined with routes like this:

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"   })
    .when("/services", {templateUrl: "partials/services.html", controller: "PageCtrl"   })
}]);

Then later I want to add/edit/override specific route(s) to resolve a promise:

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when("/services", {templateUrl: "partials/services.html", controller: "PageCtrl",  ,resolve:{getData: function(myService){return myService.getOffer();}}    })
}]);

How do I do this? The key here is adding after it was defined/configured. So this code will run at some point in the future.

Vad
  • 3,658
  • 8
  • 46
  • 81

1 Answers1

1

It is

app.run(function ($route) {
  var route = $route.routes['/...'];
  route.resolve = route.resolve || {};
  route.resolve.someResolver = ...;
});
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • This does nicely work for the page I add resolve to (eg: $route.routes['/services'];)... But when I go to other pages I get Angular Error: [$injector:unpr] – Vad Nov 03 '15 at 20:59
  • Since you use the same controller for all routes, I guess you're injecting a resolver there on the route where you didn't define this resolver. – Estus Flask Nov 03 '15 at 21:05
  • I added route.controller = "PageCtrl"; inside - but that did not fix. Is this what you refer to? – Vad Nov 03 '15 at 21:24
  • Please, post your controller code. I assume that you're injecting a resolver into the controller on the route which doesn't have this resolver. – Estus Flask Nov 03 '15 at 21:34
  • I understood. Thank you. I indeed was injecting a undefined resolver into the controller – Vad Nov 03 '15 at 21:46
  • Accepted answer. Do you know by any chance how to pass resolver to controller's $scope in a similar way. I want to use this resolver's data in routeChangeSuccess event. Thanks! – Vad Nov 06 '15 at 15:19
  • The resolver can save its resolution in any service (or better to be a shallow wrapper for the service). You may also get the control over 'resolve' resolutions in [current.$$route.locals](https://docs.angularjs.org/api/ngRoute/service/$route#$routeChangeSuccess). Feel free to post a question with your current code if you will still have problems with solving it. – Estus Flask Nov 06 '15 at 15:57
  • I posted similar question but for UI-Router instead of ngRoute http://stackoverflow.com/questions/33739533/angular-run-block-use-ui-router-stateprovider-to-resolve-promise It has bounty if you can help – Vad Nov 19 '15 at 16:49