pmn
pmn

Reputation: 2247

Asynchronously getting data in AngularJS

I want to create a label that shows the name of user who is logged in:

 <p style="color:white;font-weight:bolder;font-size:20px;padding-left:15px" title="Enter">{{userName}}  Welcome</p>

In my controller I checked if the the user was authenticated:

$scope.initial = function () {
        $http.get('Accounts/UserIsAuthenticated').success(function (response) {
            // Accounts/UserIsAuthenticated check whether user is authenticated or not, and return bool value
            debugger;
            if (response == 'True') {
                $rootScope.showLogin = false;
                $rootScope.showWelcome = true;
                $scope.userName = getUserName();
                $rootScope.showLogout = true;

            }
            else {
                $rootScope.showLogin = true;
                $rootScope.showWelcome = false;
                $rootScope.showLogout = false;
            }

        });
    };
     function getUserName() {
        $http.get('Accounts/GetUserName').success(function (response) {
            return response;
        });
    }

{{userName}} is being set to undefined though. I know that getUserName() needs time for response, so how can I fix it?

Edit: I edit my code :

$scope.initial = function () {
        $http.get('Accounts/UserIsAuthenticated').success(function (response) {
            if (response == 'True') {
                $rootScope.showLogin = false;
                $rootScope.showWelcome = true;
                getUserName().then(function (username) {
                    debugger;
                    $scope.username = username;
                });

                $rootScope.showLogout = true;

            }
            else {
                $rootScope.showLogin = true;
                $rootScope.showWelcome = false;
                $rootScope.showLogout = false;
            }

        });
    };

    function getUserName() {
        $http.get('Accounts/GetUserName');

    }

But it does not work! what is the problem?

Upvotes: 0

Views: 36

Answers (1)

devqon
devqon

Reputation: 13997

Change your getUsername to this:

function getUserName() {
    // return the promise
    return $http.get('Accounts/GetUserName');
}

Then use it like this:

if (response == 'True') {
    $rootScope.showLogin = false;
    $rootScope.showWelcome = true;
    // use the promise
    getUserName().then(function(username){
        $scope.username = username;
    });
    $rootScope.showLogout = true;
}

Or, just change your getUsername to this:

function setUserName() {
    $http.get('Accounts/GetUserName').success(function (response) {
        $scope.username = response;
    });
}

Upvotes: 1

Related Questions