I'm trying to DRY in $stateProvider
and prevent adding the same auth
function in each resolve. I've created decorator that in each state change would add this function to current state, but auth
function isn't invoked, How to fix it or how to workaround discussed issue?
app.config(function ($stateProvider, $urlRouterProvider, $provide) {
$provide.decorator('$state', function($delegate, $rootScope) {
$rootScope.$on('$stateChangeStart', function(event, state, params) {
if ($delegate.current === "login" || $delegate.current === "register") {
return;
}
console.log("decorator", $delegate);
$delegate.current.resolve = {
auth: ['AuthService', '$stateParams', function(AuthService, $stateParams) {
//how to invoke this function?
if (AuthService.isAuthenticated()) {
return AuthService.me(); //promise
} else {
return false;
}
}]
};
});
return $delegate;
});
states definition:
$stateProvider.state('root', {
abstract: true,
url: '/',
views: {
"": {
controller: 'RootCtrl',
templateUrl: 'views/root.html'
},
"header@root": {
templateUrl: 'views/header.html'
}
}
})
.state('root.home', {
url: urlPrefix,
views: {
"content@artworks": {
templateUrl: 'views/home.html',
//resolve: {
// auth: ['AuthService', '$stateParams', function(AuthService, $stateParams) {
// }]
//}
}
}
})
...
If I understand your requirement correctly, we can use native
UI-Router
built-indecorator
:decorator(name, func)
There is a working plunker
So, we can have this
var auth
And here we just use decorator with some "IF" logic
And later few our states, which will be extended by the above stuff
Check it in action here
I realized that
$delegate.current
object contains only raw stateProvider config data. To wrap resolve function I add my function to$delegate.$current
on each state change.Update
I found related discussion on github, you can add universal resolve function into
toState
param: