AngularJS:在任何部分页面控制器之前调用特定函数 [英] AngularJS: Call a particular function before any partial page controllers
问题描述
我想在应用程序加载开始时调用一个特定的函数: GetSession()
.此函数进行 $ http
调用,并从服务器获取会话令牌: GlobalSessionToken
.然后,该会话令牌将在其他控制器逻辑中使用,并从服务器获取数据.我已经在主控制器中将此调用称为 GetSession()
:在 $ routeChangeStart
事件中使用了 MasterController
,但是由于它是异步调用,因此我的代码前进到了<在 $ http
响应之前添加code> CustomerController .
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: GlobalSessionToken
from the server. This session token is then used in other controllers logic and fetch data from the server. I have call this GetSession()
in main controller: MasterController
in $routeChangeStart
event but as its an asynchronous call, my code moves ahead to CustomerController
before the $http
response.
这是我的代码:
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, status, headers, config) {
console.log(data);
});
}
我的HTML有以下部分:
And my HTML has following sections:
<body ng-app="myApp" ng-controller="MasterController">
<!--Placeholder for views-->
<div ng-view="">
</div>
</body>
如何确保始终在应用程序开始时以及在其他任何控制器调用之前始终调用此 GetSession()
.
How can I make sure this GetSession()
is always called at the very beginning of my application start and before any other controller calls and also called only once.
这是根据Maxim的答案添加 run
方法的方法.仍然需要找出一种方法,直到等待 $ http
调用返回,然后再继续使用控制器.
This is how I added run
method as per Maxim's answer. Still need to figure out a way to wait till $http
call returns before going ahead with controllers.
//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,
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;
}
推荐答案
您不能推迟控制器的初始化.
You can't postpone the initialisation of controllers.
您可以将控制器代码放入Session promise回调中:
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.
这篇关于AngularJS:在任何部分页面控制器之前调用特定函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!