Not possible to add state.resolve from $stateChangeStart event
Overview: Sometimes it's desirable to add state resolves on the fly, instead of needing to add them to all states beforehand. For example, a resolve that verifies a user is authenticated or fetches the user from an API.
It's possible to do this with $routeChangeSuccess using the following code:
// @see http://stackoverflow.com/a/18245378/1738217
function authenticate() {
if ( user.isAuthenticated ) {
return;
}
// simulate deferred
return $timeout(function() {
user.isAuthenticated = true;
}, 3000);
}
$rootScope.$on( "$routeChangeStart", function( e, next ) {
next.resolve = angular.extend( next.resolve || {}, {
__authenticating__: authenticate
});
});
However the same is not possible with $stateChangeSuccess. This is because the event is broadcast with to.self, see this line. This means if you add a resolve in the $stateChangeSuccess event, you are actually adding on to.self.resolve which is never considered for resolve.
_Related:_ https://github.com/angular-ui/ui-router/issues/1153
Seems like it could be handy.
Same problem here. I can't add a custom resolve dynamically so I have to hack this way:
$stateProvider
.state("home", {
url: "/",
resolve: {} // add {} default
})
Interestingly, resolve is one of the only fields on state that can't be decorated via the standard API. However, you can decorate it another, uglier way.
// Need access to both state representations. Decorate any attribute to access private state object.
$stateProvider.decorator('path', function(state, parentFn) {
if (state.self.resolve === undefined) {
state.self.resolve = {};
state.resolve = state.self.resolve;
}
return parentFn(state);
});
:+1: very useful.
I sometimes load additional resources (css/js/images..) before showing a route, making sure it's fully loaded. I'm switching now to ui-router and encountered this issue.
As @NecoleYu wrote (thanks!), initializing the state definitions with resolve: {} gives access to the actual resolve object that is used internally by ui-router, and allows to add resolves within $stateChangeStart.
$stateProvider
.state 'home',
url: "/"
resolve: {}
...
$rootScope.$on '$stateChangeStart', (e, toState, toParams, fromState, fromParams) ->
toState.resolve.x = ->
$timeout ->
alert "done"
, 3000
but would be nicer not to need this.
@elado Agree
@elado Very useful follow up comment
Oh that possibillity would be wonderful!
Need it so much. Very handy. +1
I'd love to see this as well. I wasn't able to make @christopherthielen's workaround work, though I was scratching my head as to why. Perhaps it depends on the nesting. Stepping through it, it appears the decoration has to happen before the state building is queued, for whatever reason. No hooks to work with there so for now I wrapped $stateProvider.state, decorating the config before passing it onto the original implementation. If anyone has a better solution I'd love to hear it.
+1. That would be really helpful!
also struggeld with this problem because some states had a defined resolve object and some did not. Took me forever to figure out why this was not working with all states:
if (!toState.resolve) { toState.resolve = {} };
toState.resolve.pauseStateChange = [ '$q', ($q: ng.IQService) => {...})];
Now i use the decorator suggested by @christopherthielen ! Thanks :)
But it should be possible to extend the resolve method without this "hack"! :+1:
Thanks all for the comments, this is gold! :) :+1:
We've added this capability to the 1.0 code:
https://github.com/angular-ui/ui-router/blob/feature-1.0/src/transition/transition.ts#L162-L172
app.run(function ($transitions) {
// register global transition start hook
$transitions.onStart({ from: '*', to: '*' }, function($transition$) { // inject the Transition instance
$transition$.addResolves({
newResolve: function(MyService) {
return MyService.someAsyncThing();
}
});
});
});
Alternatively, if you just want to delay the transition, you can return a promise from the hook:
app.run(function ($transitions) {
// register global transition start hook
$transitions.onStart({ from: '*', to: '*' }, function(MyService, $q) {
return MyService.waitForAsyncThing().then(function(data) {
if (data.failure) return $q.reject("Failed thing, cancel transition");
});
});
});
@christopherthielen I tried to use this method for ACL, but I'm running into a problem prevent route change if route/state rejected.
If I use onStart, I can't access $state$ (toState). $state$ is not exposed and error occurs. If I use onEnter, then I don't seem to be able to prevent the route from changing.
$transitions.onEnter({ from: '*', to: '*' }, function($state$, $q, acl) {
var requiredPermissions = getRequiredPermissions($state$);
return acl.ready().then(function(acl) {
if (!acl.can(requiredPermissions)) {
// Rejection seems to prevent individual state/view change,
// but doesn't prevent route change
return $q.reject({ reason: 'acl' });
}
});
});
I haven't tried using addResolves yet. I previously had this working using ngRoute with resolves. The transition handler seems to be more appropriate for this case.
Tried using addResolves, but that doesn't seem to be doing it either:
$transition$.addResolves({
controllerAcl: function() {
console.log('running resolve');
var deferred = $q.defer();
acl.ready(function(acl) {
if (acl.can(requiredPermissions)) {
console.log('resolved');
deferred.resolve(toState);
} else {
console.log('rejected');
deferred.reject({ reason: 'acl' });
}
});
return deferred.promise;
}
});
I get no console logs.
If I use onStart, I can't access $state$ (toState). $state$ is not exposed and error occurs.
You should inject $transition$ and use var toState = $transition$.to()
If I use onEnter, then I don't seem to be able to prevent the route from changing.
Odd, that should stop the state change...
edit: yes, it should stop the state change. Check the console trace: http://plnkr.co/edit/6hWLzBGawc8VcjKvNGHi?p=preview
@christopherthielen
should inject $transition$ and use var toState = $transition$.to()
Yep, that works. Though, now I'm wondering why to/from are functions.
Odd, that should stop the state change...
After some testing I found that if I use ui-sref then the route properly never changes to the rejected route, but when I use href or just type the rejected route into the location bar, the state change is rejected (views remain on previous states), but the URI in the location bar remains the rejected route. I would have expected the previously valid route to overwrite the rejected URI in the location bar. Is there another step I need to do to prevent directly navigating to invalid routes (those where I return a reject from onStart)?
Also, $stateChangeError doesn't fire when a rejection is returned from onStart
Yep, that works. Though, now I'm wondering why to/from are functions.
The to/from object defines the Transition-matching criteria. They are used to determine if the hook should be applied to a transition or not. You can use a glob or a function. The function can inspect the to state or from state to determine if the hook should be applied to the transition.
See how this hook works: https://github.com/ui-router/sample-app/blob/master/app/routerhooks/redirectTo.js
when I use href or just type the rejected route into the location bar, the state change is rejected (views remain on previous states), but the URI in the location bar remains the rejected route.
I think you are describing #2455 which is fixed in master
Also, $stateChangeError doesn't fire when a rejection is returned from onStart
Did you re-enable the deprecated state events by adding ng1/stateEvents.js?
See the release notes for what I'm referring to: https://github.com/angular-ui/ui-router/releases/tag/1.0.0alpha0
All state events, (i.e. $stateChange* and friends) are deprecated and disabled by default; re-enable them by including the ng1/stateEvents.js file, and depend on the ui.router.state.events angular module in your application.