简体   繁体   中英

AngularJS: Passing variables between controllers

I am new to angular and I'm trying to find a method of passing variables between controllers. I saw the best method of achieving this was by using a service, as shown here - AngularJS: How can I pass variables between controllers?

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. 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 .

this.GetLoginUsername = function () {
    return loggedInUser[0].Username;
}

Also, as stated in comments either use ngRoute/uiRouter to change the page/url...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM