我试图在服务中保存季节令牌,但每次加载新页面时,服务器似乎都会自行重置
angular.service.js:
var appBooking = angular.module('Booking');
appBooking.service('WebService', ['$http', '$rootScope', function ($http, $rootScope) {
this.setToken=function (tkn){
$rootScope.token=tkn;
};
this.getToken=function () {
return($rootScope.token);
};
this.login = function (user, password) {
var dato={'usuario':{'username': user, 'password': password}};
return $http.post('http://localhost:8080/Booking/login',dato);
};
}]);
angular_apps.js:
angular.module('Booking', []);
angular_controllers.js:
var appBooking = angular.module('Booking');
appBooking.controller('CtrlLogin', ['$scope', 'WebService', function ($scope, WebService) {
var self = this;
self.login = function (user, password) {
WebService.login(user, password)
.then(function (jsonObject) {
console.log("Login success");
location = "profilepage.html";
token = jsonObject.data.token;
WebService.setToken(token);
}, function errorCallBack(response){
console.log("Login failed");
});
};
}]);
控制器LoginController附加到登录表单并正确设置值,但是当我加载新页面时,$ rootScope.token未定义。
在html页面中,我加载了与LoginController在同一文档中定义的控制器,例如:
appBooking.controller('CtrlProfile', ['$scope', 'WebService', function ($scope, WebService) {
//content here
}]);
在每个html文件中的每个标记之前,我加载以下脚本
<script src="../js/angular.js"></script>
<script src="../js/angular_apps.js"></script>
<script src="../js/angular_services.js"></script>
<script src="../js/angular_controllers.js"></script>
我做错了什么?
答案 0 :(得分:0)
Fo AngularJS不重新加载您的服务,您需要确保AngularJS正在处理所有必要的应用内路由。您如何处理页内路线更改?对于您的代码:
var appBooking = angular.module(&#39; Booking&#39;);
appBooking.controller('CtrlLogin', ['$scope', 'WebService', function ($scope, WebService) {
var self = this;
self.login = function (user, password) {
WebService.login(user, password)
.then(function (jsonObject) {
console.log("Login success");
// What is this line supposed to do????
location = "profilepage.html";
token = jsonObject.data.token;
WebService.setToken(token);
}, function errorCallBack(response){
console.log("Login failed");
});
};
}]);
您的作业为location
。如果用于更改浏览器位置,并且Angular JS应用程序不处理浏览器位置更改,则浏览器页面将重新加载,并且您的Angular JS应用程序将重置。