0

I have defined a factory auth as follows:

app.factory('auth', [function () {
    var auth = {};

    auth.getUser = function () {
        ... ...
        // get user from cookie, cache, history, etc.
    }

    return auth
}]);

For many pages, I want to always run auth.getUser() before displaying them. To this end, at the moment, I use resolve, eg:

.state('home', {
    url: '/home',
    templateUrl: '/htmls/home.html',
    controller: 'MainCtrl',
    resolve: { getUser: ['auth', function (auth) { return auth.getUser() }]}
 })

The pitfall of this implementation is I have to write lots of resolve. Thus, I am wondering if there is a way to implement this rule in controllers rather than state. Could anyone help?

SoftTimur
  • 5,630
  • 38
  • 140
  • 292
  • 3
    Possible duplicate of [Initialize AngularJs app before calling the controllers](https://stackoverflow.com/questions/47391797/initialize-angularjs-app-before-calling-the-controllers) – Estus Flask Nov 21 '17 at 04:45
  • 1
    As for specifying a resolver automatically for all routes, see https://stackoverflow.com/a/33813535/3731501 – Estus Flask Nov 21 '17 at 04:53

2 Answers2

0

Try checking the condition in

$rootScope.$on('$stateChangeStart', function (event, toState) {
  //condition here and $state.go('')
});

I'm not sure if this works.

0

use angular run function
app.run(function() {
    alert(1);
});

see http://jsfiddle.net/ysq3m/

Manoj Meria
  • 586
  • 6
  • 13