javascript - AngularJS - 等待异步调用

标签 javascript angularjs

我开始学习 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 是应该注入(inject) Controller 的依赖关系图。如果任何映射对象是函数,函数将被评估并注入(inject)它们的返回值。如果一个函数返回一个 promises,在 promise 被 resolved 之前, View 不会被渲染。

仅供引用,如果 promise 被拒绝,则根本不会呈现 View 。您可能希望在 $rootScope.$on('routeChangeError', functionToHandleRejection) 中处理这种情况

这是一个适合您的示例:

.when('someUrl', {
  resolve: {
    object: function(AuthenticationSharedService) {
      return AuthenticationSharedService.login();
    }
  }
})

关于javascript - AngularJS - 等待异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23000136/

相关文章:

angularjs - 如何测试模块的运行 block

java - 跳过 Spring 中的 CORS 并配置项目以使用 Aptana

javascript - 如何 trim 多个字符?

javascript - 如何将我的 javascript 文件加载到嵌套在 View 中的局部 View 中? MVC5

javascript - 脚本没有正确接收 url

javascript - 我是否应该使用 jQuery 对话框?

javascript - 通过更改构造函数属性动态替换原型(prototype)

angularjs - 你如何在 AngularFire 0.5.0 中从 .$on ('loaded' )访问加载的数据

unit-testing - AngularJS 测试示例

javascript - 从 Firebase、angularJS 检索日期