$ rootscope没有持有价值

我正在使用以下代码在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设置为超出$ http.get方法范围的pqr

编辑:添加了右括号。

尼克斯

应该将其关闭,因为它存在异步问题...运行此代码,您将看到。

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);
 });

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章