AngularJS: Call a particular function before any partial page controllers

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

提交回复
热议问题