3

Let's say in 90-95% of my routes I need to check if user is in (let's say jail). Then, I'm currently doing something like:

$routeProvider
    .when("/news", {
        templateUrl: "newsView.html",
        controller: "newsController",
        resolve: {
            injail: function(jailservice){
                return jailservice.injail();
        }
    }
})

Do I really need to do this resolve on each route? (the routes are in different folders, each route file contains route for a specific module).

Is it something better I can do than call the resolve injail on every route?

George Kagan
  • 5,913
  • 8
  • 46
  • 50
maria
  • 207
  • 5
  • 22
  • 56

1 Answers1

3

A few options.

Option 1 - use parent state with resolve

$stateProvider
    .state('parent', {
        resolve:{
            resA: function () {}
        }
    })
    .state('parent.child', {
        // resA from parent state available to all child states
        controller: function (resA) {}
    });

More info

Option 2 - external resolve functions (less duplicated code)

Declaration:

resolve: {
    myResolve: myResolve
}

If using ES2015, you can shorten it to resolve: {myResolve} (see enhanced object literals)

Definition (in a separate file containing all resolves):

myResolve.$inject = ['myService'];
function myResolve(myService) {
    return myService.getStuff();
}

More info

EDIT - example using your code:
In your routes declaration, change resolve to: resolve: {injail: injailResolve}

In separate file, the definition:

injailResolve.$inject = ['jailservice'];
function injailResolve(jailservice) {
    return jailservice.injail();
}
Community
  • 1
  • 1
George Kagan
  • 5,913
  • 8
  • 46
  • 50
  • Think so, but it will require you to change the structure of your routes, can be quite some work... Option 2 is more straightforward. – George Kagan Oct 06 '16 at 11:18
  • how would the myservice injection look like? could you provide an example of that file too? – maria Oct 06 '16 at 11:23
  • It's just a flat JS file with each resolve defined as above (see Definition). The functions are global so make sure to make them unique. The `$inject` bit will be used by angular at run-time to inject the actual service. – George Kagan Oct 06 '16 at 11:27
  • a flat js file With for example one of them are like: injail: function(jailservice){ return jailservice.injail(); }? – maria Oct 06 '16 at 11:30
  • or is it a acual factory/service im injecting? – maria Oct 06 '16 at 11:34