Angularjs 使用一次性密钥限制路由访问

Angularjs 使用一次性密钥限制路由访问,angularjs,Angularjs,我在登录控制器上使用此方法返回用户对象 .controller('loginController', function ($scope, $http, $location) { $scope.login = function (user) { var credentials = { Email: user.email, Password: user.password } $http.post('api/Login/Validate', credential

我在登录控制器上使用此方法返回用户对象

.controller('loginController', function ($scope, $http, $location) {
    $scope.login = function (user) {
        var credentials = { Email: user.email, Password: user.password }
        $http.post('api/Login/Validate', credentials)
            .success(function (data) {
                console.log(data);
                $scope.user = data;
                $location.path("/index");
        }).error(function (data) {
            console.log(data);
            $scope.user = null;
            });
        };
});
在Chrome控制台中,我返回以下对象:

Object {Admin: false Email: "email@email.com" Id: 12 OneTimeKey: "random string here"}
当该方法尝试导航到“索引”时,它使用以下路径:

.when('/index', {
            templateUrl: '/Client/Views/index.html',
            controller: 'dashController',
            resolve: {
                oneTimeKey: function ($http) {
                    return $http.post('api/Login/VerifyOneTimeKey?oneTimeKey=' + OneTimeKey);
                }
            }
        })
但我得到了以下错误:

ReferenceError: OneTimeKey is not defined
at $routeProvider.when.when.when.resolve.oneTimeKey
我假设我得到这个错误是因为resolve无法在当前范围内获取OneTimeKey变量,但我可能错了。不确定如何从这里解决此问题。

请查看您何时可以传递到的选项。eggHead.io上有一段很好的视频:

基本上,您可以这样做,在路由加载时检查服务器,并有条件地阻止它加载

.when('/index', {
    templateUrl: '/Client/Views/index.html',
    controller: 'mainController',
    resolve: {
        oneTimeKey: function($http) {
            //The route will only be loaded if this promise resolves.
            return $http.get('api/oneTimeKey');
        }
    }
})
如果要在控制器中加载令牌,则必须将其存储在服务中,以便可以从解析中访问它。e、 g:

app = angular.module('myApp');

var UserSession = function() {

}

UserSession.prototype.initialize = function(session) {
    this.session = session;
}

app.service('userSession', UserSession);


app.controller('loginController', function ($scope, $http, $location, userSession) {
    $scope.login = function (user) {
        var credentials = { Email: user.email, Password: user.password }
        $http.post('api/Login/Validate', credentials)
            .success(function (data) {
                $scope.user = data;
                userSession.initialize(data);
                $location.path("/index");
        }).error(function (data) {
            //...
        });
    };
});

...

.when('/index', {
    templateUrl: '/Client/Views/index.html',
    controller: 'dashController',
    resolve: {
        oneTimeKey: function ($http, userSession) {
            return $http.post('api/Login/VerifyOneTimeKey?oneTimeKey=' + userSession.session.OneTimeKey);
        }
    }
})

我对我的问题进行了编辑,直到我无法实现你的答案为止。我想知道你是否能进一步说明。非常感谢。@Rex_C我编辑了我的答案,以显示如何从解析函数访问一次性令牌