Search code examples
angularjsnode.jsangular-ui-routermean-stackmeanjs

Angular Router - Using abstract state to access service


Using mean.js:

I have a large application that is divided by say, offices. Each office accesses the same application in the same way, but employees of an office may only access information pertaining to that office. Company administrators may access the app fully, switching between office contexts. The caveat is that there are no user accounts (no login/auth) for office employees, only admin accounts for the administrators.

I'm exploring doing it in the following way:

I created an access module with a service that stores the office context, passing it to the backend when making API calls. This is set upon application startup from config files.

This is well and good, but I need to allow the administrators to switch office contexts. I use a link <a ui-sref="Context({ officeID: 'x' }) (in the navbar dropdown, so accessible from every state) to access the angular router:

.state('Context', {
        url: '/Context/:officeID',
        controller: 'ContextController',
        controllerAs: 'vm'
      });

This passes the officeID to the ContextController, which would set the ContextService.officeID variable. At this time, I believe I would make an api call from the ContextController to refresh the current state's data to reflect the current context. Not sure how to do that.

I feel that I have some options here, which I am unsure how to implement:

  • I can make the Context state abstract, and every other state a child, but that seems bulky. If this is correct, how do I tell the current state to refresh it's data?
  • I could enter the Context state, set the ContextService.officeID, and immediately redirect back to the previous state, which upon entering, should make an api call using the new context. If this is correct, how do I properly perform that redirect?

I could scrap how this is being done entirely, but I don't know where I would start. Any advice is welcome.


Solution

  • I figured out something that feels a bit more elegant.

    I still use the Context route. I've included the ContextService in all of my angular modules, and call it when the context needs to be set. I tried to redirect using $location.path(...), which was a major headache. Using $state.go($state.previous.state.name) works a treat.

    Even better, if you use routes that depend on resolves, you can further redirect using $state.go($state.previous.state.name, $stateParams);