在AngularJS中异步获取数据

时间:2016-01-12 14:16:19

标签: angularjs asp.net-mvc

我想创建一个标签,显示登录用户的姓名:

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

在我的控制器中,我检查了用户是否经过身份验证:

$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}}虽然设置为undefined。我知道getUserName()需要时间来回复,所以我该如何解决?

编辑:我编辑我的代码:

$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');

    }

但它不起作用!有什么问题?

1 个答案:

答案 0 :(得分:1)

将您的getUsername更改为:

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

然后像这样使用它:

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

或者,只需将您的getUsername更改为:

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