我在登录控制器上使用此方法返回用户对象
.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"}
当该方法尝试导航到' index'时,它使用以下路线:
.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
我假设我收到此错误,因为解析无法在当前范围内获取OneTimeKey变量,但我可能错了。不知道如何从这里解决这个问题。
答案 0 :(得分:0)
查看可以传递到when()
的{{3}}选项。 eggHead.io上有一个很好的视频:resolve
基本上你可以做这样的事情来检查服务器何时加载路由并有条件地阻止它加载。
.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);
}
}
})