[英]AngularJS: Passing variables between controllers
I am new to angular and I'm trying to find a method of passing variables between controllers. 我对angular并不陌生,我试图找到一种在控制器之间传递变量的方法。 I saw the best method of achieving this was by using a service, as shown here - AngularJS: How can I pass variables between controllers?
我看到实现此目标的最佳方法是使用服务,如下所示-AngularJS:如何在控制器之间传递变量?
However, this doesn't seem to be working with my code, as I will explain at the bottom. 但是,这似乎不适用于我的代码,正如我将在底部解释的那样。
Here is my service code, 这是我的服务代码,
app.service('loginService', function ($http) {
var loggedInUser = []
//If the login was successful this will be used
this.setLoginDetails = function(userDetails){
loggedInUser.push(userDetails);
}
this.GetLoginUsername = function () {
return loggedInUser.Username;
}
});
And now my two controllers, 现在我的两个控制器,
app.controller('loginController', function ($scope, $rootScope, loginService, $location, $window) {
$scope.authenticateLogin = function () {
// get record
var user = {
Username: $scope.username,
Password: $scope.password
};
var promisePost = loginService.post(user);
promisePost.then(function (result) {
var res = result.data;
//This is the important line
loginService.setLoginDetails(user);
$window.location.href = loginPageUrl;
},
function (errorResult) {
console.log("Unable to log in : " + errorResult);
});
}
});
my Controller that is trying to retrieve the information that has been set, 我的控制器正在尝试检索已设置的信息,
app.controller('userController', function ($scope, userService, $window, $modal, loginService) {
// Get the current logged in user
$scope.LoggedInAs = loginService.GetLoginUsername();
});
The issue I am having is that the username is being correctly set with the first controller, but when I try to access that information with the second controller the value for loggedInUser in null so the value is not being saved between the controllers. 我遇到的问题是,使用第一个控制器正确设置了用户名,但是当我尝试使用第二个控制器访问该信息时,loginInUser的值将为null,因此不会在两个控制器之间保存该值。 What am I doing wrong?
我究竟做错了什么?
var loggedInUser = []
is an array, so if you want to get username you will have to do loggedInUser[0].Username
and not loggedInUser.Username
. var loggedInUser = []
是一个数组,所以如果你想获得的用户名,你将不得不做loggedInUser[0].Username
而不是loggedInUser.Username
。
this.GetLoginUsername = function () {
return loggedInUser[0].Username;
}
Also, as stated in comments either use ngRoute/uiRouter to change the page/url... 另外,如注释中所述,可以使用ngRoute / uiRouter更改页面/ URL ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.