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?

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Think so, but it will require you to change the structure of your routes, can be quite some work... Option 2 is more straightforward.
how would the myservice injection look like? could you provide an example of that file too?
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.
a flat js file With for example one of them are like: injail: function(jailservice){ return jailservice.injail(); }?
or is it a acual factory/service im injecting?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.