0

我正在使用以下代码在 rootscope 中存储用户名('pqr')值,但它的范围是 $http.get mehtod

angular.module('myApp').run(function ($rootScope,$http) {
    $rootScope.username = 'abc';
    $http.get('/api/getuser')
        .success(function(data) {
            console.log("logged in user is: "+data);
            $rootScope.username = data;
        });
    $rootScope.$on('$routeChangeStart', function (event, next) {
    });
    console.log("logged in user after setting: " + $rootScope.username);
});

控制台日志输出为:

logged in user is: pqr
logged in user after setting: abc

如何将 $rootScope.username 设置为 pqr 超出 $http.get 方法的范围

编辑:添加了右括号。

4

1 回答 1

1

这应该被关闭,因为它是一个异步问题......运行这段代码,你会看到。

angular.module('myApp').run(function ($rootScope,$http) {
 $rootScope.username = 'abc';
 var $promise = $http.get('/api/getuser')
    .success(function(data) {
      console.log("logged in user is: "+data);
      $rootScope.username = data;
    });
 $rootScope.$on('$routeChangeStart', function (event, next) {

 });
 $promise.then(function(){
     console.log("logged in user after setting: "+$rootScope.username);
 });
于 2014-04-18T13:29:52.680 回答