DevShadow DevShadow - 17 days ago 10
AngularJS Question

Angular Controller/Factory Working Out Of Order

I have the following factory and controller:

(function () {
'use strict';
angular.module('app.core')
.factory('Auth', ['$http', function AuthFactory($http) {

return {
NavAuth: function (Tab) {
return $http({ method: 'GET', url: 'Dashboard/AuthorizeNavItem', params: { Name: Tab } });
}
}

}]);
})();


angular
.module('myapp')
.controller('IndexController', ['fuseTheming', 'msNavigationService', 'Auth', function (fuseTheming, msNavigationService, Auth) {
var vm = this;

//Define the tabs
msNavigationService.saveItem('app', {
title: 'QPSTool',
group: true,
weight: 1
});

msNavigationService.saveItem('app.dashboard', {
title: 'Dashboard',
icon: 'icon-tile-four',
state: 'app.dashboard',
weight: 1
});

Auth.NavAuth('IT').success(function (result) {
if (result == 'Authorized') {
msNavigationService.saveItem('app.it', {
title: 'IT',
icon: 'icon-monitor',
weight: 2
});
}
});

Auth.NavAuth('Users').success(function (result) {
if (result == 'Authorized') {
msNavigationService.saveItem('app.it.users', {
title: 'Users',
state: 'app.it.users',
weight: 1
});
}
});

Auth.NavAuth('Admin').success(function (result) {
if (result == 'Authorized') {
msNavigationService.saveItem('app.admin', {
title: 'Admin',
icon: 'icon-radioactive',
weight: 3
});
}
});

Auth.NavAuth('NavControl').success(function (result) {
if (result == 'Authorized') {
msNavigationService.saveItem('app.admin.navcontrol', {
title: 'Navigation Auth',
state: 'app.admin.navcontrol',
weight: 1
});
}
});

// Data
vm.themes = fuseTheming.themes;
}]);


What the factory method NavAuth does is it takes a navigation item name as a parameter and tells us whether a user is allowed to access this item.

The issue I am having is that in the controller when I use
msNavigationService.saveItem
data is being returned in a random order. So It will return the authorized for
NavControl
before
IT
.

This causes the side navigation to not render correctly.

How do I make it so that things will run in the order that I have specified in the controller (i.e. how do i make it wait until one is done to do the other)?

Answer

I think your issue would not be resolved by $q.all but by putting the then part of the promise, so you would do something like

NavAuth('IT').then(function (res) {
  doWhatever IT function does;
  NavAuth('NavControl').then(function (res) {
    doWhatever NavControl function does;
  })
})

With the then of the promises you enforce the code to be executed in an order, with $q.all() you won't execute everything untill all the promises you pass to the $q.all() have finished, and that is not what you want

Comments