My question or situation pertains to the states defined in my AngularJS application. Here is an example of how I have them structured:
$stateProvider
.state('myApp', {
abstract: true,
template: '<ui-view/>'
})
.state('myApp.stateOne', {
url: 'state1',
templateUrl: '/an/views/state-1.html',
controller: 'StateOneCtrl'
})
.state('myApp.stateTwo', {
url: 'state2',
templateUrl: '/an/views/state-2.html'
controller: 'StateTwoCtrl'
})
.state('myApp.stateThree', {
url: 'state3',
templateUrl: '/an/views/state-3.html'
controller: 'StateThreeCtrl'
})
In this scenario, if I need to verify whether a user is permitted to access 'mayApp.stateThree'
, I typically make a backend request. This is handled by a service (in this case, named IsAllowedService
). Normally, I would include the logic for this check in the .run()
block within my app.js file, as shown below:
.run(['IsAllowedService', '$state', function (IsAllowedService, $state) {
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
// Check if we are trying to access myApp.stateThree and determine permission...
if (toState.name === 'myApp.stateThree') {
IsAllowedService.checkIfIsAllowed().then(function (resp) {
if(resp.allowed === false) {
$state.go('myApp.stateOne');
}
});
}
});
}]);
While the above method works fine, it does not wait for the service response before loading 'mayApp.stateThree'. As a result, there is a quick display of the page before redirection occurs. I could replicate the same code in the 'StateThreeCtrl' but the flash issue persists. Is there a way to address this during state definition? For instance, something like the hypothetical code snippet below:
.state('myApp.stateThree', {
url: '/an/state3',
templateUrl: '/an/views/state-3.html'
controller: 'StateThreeCtrl',
resolve: {
isAllowed : function () {
IsAllowedService.checkIfIsAllowed().then(function (resp) {
return resp;
})
}
}
It is evident that directly injecting services such as $http
may not be feasible, but is there a method to delay the rendering of the view / controller for 'mayApp.stateThree' until the result from
IsAllowedService.checkIfIsAllowed()
is obtained? Any guidance on structuring my application/code would be welcomed. Despite using ng-cloak in the HTML view, it did not resolve the issue!