AngularJS: Call a particular function before any partial page controllers

后端 未结 3 1035
青春惊慌失措
青春惊慌失措 2021-02-08 03:19

I want to call a particular function: GetSession() at the beginning of my application load. This function makes a $http call and get a session token: <

3条回答
  •  情深已故
    2021-02-08 04:03

    Even though some of the solutions here are perfectly valid, resolve property of the routes definition is the way to go, in my opinion. Writing your app logic inside session.then in every controller is a bit too much , we're used such approach too in one of the projects and I didn't work so well.

    The most effective way is to delay controller's instantiation with resolve, as it's a built-in solution. The only problem is that you have to add resolve property with similar code for every route definition, which leads to code duplication.

    To solve this problem, you can modify your route definition objects in a helper function like this:

    function withSession(routeConfig) {
      routeConfig.resolve = routeConfig.resolve || {};
    
      routeConfig.resolve.session = ['getSessionPromise', function(getSessionPromise) {
         return getSessionPromise();
      }]
    
      return routeConfig;
    } 
    

    And then, where define your routes like this:

    $routeProvider.when('/example', withSession({
      templateUrl: 'views/example.html',
      controller: 'ExampleCtrl'
    }));
    

    This is one of the many solutions I've tried and liked the most since it's clean and DRY.

提交回复
热议问题