AngularJS: Call a particular function before any partial page controllers

后端 未结 3 1036
青春惊慌失措
青春惊慌失措 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.

    0 讨论(0)
  • 2021-02-08 04:18

    You have not provided any details related to GetSession. For scenarios like this you should use the resolve property while defining your routes in $routeProvider. I see you are using resolve already.

    What you can do now is to wrap the GlobalSessionToken into a Angular service like GlobalSessionTokenServiceand call it in the resolve to get the token before the route loads. Like

    resolve: { 
                loadData: function($q){ 
                    return LoadData2($q,'home'); 
                },
                GlobalSessionToken: function(GlobalSessionTokenService) {
                     return GlobalSessionTokenService.getToken()  //This should return promise
                }
             } 
    

    This can then be injected in your controller with

    controllers.MasterController = function($rootScope, $http,GlobalSessionToken){

    0 讨论(0)
  • 2021-02-08 04:21

    You can't postpone the initialisation of controllers.

    You may put your controller code inside a Session promise callback:

    myApp.factory( 'session', function GetSession($http, $q){
        var defer = $q.defer();
    
        $http({
            url: GetSessionTokenWebMethod,
            method: "POST",
            data: "{}",
            headers: { 'Content-Type': 'application/json' }
        }).success(function (data, status, headers, config) {
            GlobalSessionToken = data;
            defer.resolve('done');
        }).error(function (data, status, headers, config) {
            console.log(data);
            defer.reject();
        });
    
        return defer.promise;
    } );
    
    myApp.controller( 'ctrl', function($scope,session) {
       session.then( function() {
          //$scope.whatever ...
       } ); 
    } );
    

    Alternative: If you don't want to use such callbacks, you could have your session request synchronous, but that would be a terrible thing to do.

    0 讨论(0)
提交回复
热议问题