[英]AngularJS - Waiting for an asynchronous call
我开始学习AngularJS,到目前为止一直很好,但我目前仍然关注一个关于同步函数的小问题。
我想在执行其余代码之前调用并返回函数AuthenticationSharedService.login()
。 我怎样才能做到这一点?
app.js
myApp.config(['$routeProvider', '$httpProvider', 'USER_ROLES',
function ($routeProvider, $httpProvider, USER_ROLES) {
$routeProvider
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginController',
access: {
authorizedRoles: [USER_ROLES.all]
}
})
.when('/error', {
templateUrl: 'views/error.html',
access: {
authorizedRoles: [USER_ROLES.all]
}
})
.otherwise({
templateUrl: 'views/main.html',
controller: 'MainController',
access: {
authorizedRoles: [USER_ROLES.user]
}
});
}])
.run(['$rootScope', '$location', 'AuthenticationSharedService', 'Session', 'USER_ROLES',
function($rootScope, $location, AuthenticationSharedService, Session, USER_ROLES) {
$rootScope.$on('$routeChangeStart', function (event, next) {
<!-- Bit of code to execute before going further -->
if (!Session.login) {
console.log('First attempt to login');
AuthenticationSharedService.login();
}
<!-- /////////////////////////////////////////// -->
if (AuthenticationSharedService.isAuthenticated()) {
// user is not allowed
$rootScope.$broadcast("event:auth-notAuthorized");
} else {
// user is not logged in
$rootScope.$broadcast("event:auth-loginRequired");
}
});
}]);
authenticationSharedService.js
myApp.factory('AuthenticationSharedService', ['$rootScope', '$http', '$cookieStore', 'authService', 'Session', 'Account',
function ($rootScope, $http, $cookieStore, authService, Session, Account) {
return {
login: function () {
return Account.get(function(data) {
Session.create(data.login, data.roles);
authService.loginConfirmed(data);
});
}
};
}]);
你需要使用解决方案。 请参阅http://docs.angularjs.org/api/ngRoute/provider/ $ routeProvider或http://www.bfcamara.com/post/66001429506/authentication-in-a-spa-with-angular-此第二个链接是挺好的
Resolve是应该注入控制器的依赖关系的映射。 如果任何映射对象是函数,则将评估函数并注入其返回值。 如果函数返回promises,则在解析promise之前不会呈现视图。
仅供参考,如果承诺被拒绝,则根本不会呈现视图。 您可能希望在$ rootScope中处理这种情况。$ on('routeChangeError',functionToHandleRejection)
这是一个适合您的示例:
.when('someUrl', {
resolve: {
object: function(AuthenticationSharedService) {
return AuthenticationSharedService.login();
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.