我想在我的应用程序加载开始时调用一个特定的函数:GetSession().此功能使$http调用并从服务器获取会话令牌:GlobalSessionToken.然后,该会话令牌用于其他控制器逻辑和从服务器获取数据.我在主控制器中调用了GetSession():$PathChangeStart事件中的MasterController,但作为异步调用,我的代码在$http响应之前前进到CustomerController.
这是我的代码:
var GlobalSessionToken = ''; //will get from server later //Define an angular module for our app var myApp = angular.module('myApp',['ngRoute']); //Define Routing for app myApp.config(['$routeProvider',function ($routeProvider) { $routeProvider. when('/customer',{ templateUrl: 'partials/customer.html',controller: 'CustomerController',resolve: { loadData: function($q){ return LoadData2($q,'home'); } } }). otherwise({ redirectTo: '/home' }); }]); //controllers start here and are defined in their each JS file var controllers = {}; //only master controller is defined in app.js,rest are in separate js files controllers.MasterController = function($rootScope,$http){ $rootScope.$on('$routeChangeStart',function(){ if(GlobalSessionToken == ''){ GetSession(); } console.log('START'); $rootScope.loadingView = true; }); $rootScope.$on('$routeChangeError',function(){ console.log('ERROR'); $rootScope.loadingView = false; }); }; controllers.CustomerController = function ($scope) { if(GlobalSessionToken != ''){ //do something } } //adding the controllers to myApp angularjs app myApp.controller(controllers); //controllers end here function GetSession(){ $http({ url: GetSessionTokenWebMethod,method: "POST",data: "{}",headers: { 'Content-Type': 'application/json' } }).success(function (data,status,headers,config) { GlobalSessionToken = data; }).error(function (data,config) { console.log(data); }); }
而我的HTML有以下几个部分:
<body ng-app="myApp" ng-controller="MasterController"> <!--Placeholder for views--> <div ng-view=""> </div> </body>
如何确保GetSession()始终在我的应用程序启动开始之前以及任何其他控制器调用之前调用,也只调用一次.
编辑:这是我如何按照Maxim的答案添加运行方法.仍然需要找出一种等待$http调用返回的方法,然后再继续执行控制器.
//Some initializing code before Angular invokes controllers myApp.run(['$rootScope','$http','$q',function($rootScope,$http,$q) { return GetSession($http,$q); }]); function GetSession($http,$q){ var defer = $q.defer(); $http({ url: GetSessionTokenWebMethod,config) { GlobalSessionToken = data; defer.resolve('done'); }).error(function (data,config) { console.log(data); defer.reject(); }); return defer.promise; }
解决方法
您不能推迟控制器的初始化.
您可以将控制器代码放在Session promes回调中:
myApp.factory( 'session',function GetSession($http,config) { console.log(data); defer.reject(); }); return defer.promise; } ); myApp.controller( 'ctrl',function($scope,session) { session.then( function() { //$scope.whatever ... } ); } );
替代方法:如果你不想使用这样的回调,你可以让你的会话请求同步,但这是一件可怕的事情.