我使用以下代码在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
编辑:添加了右括号。
答案 0 :(得分: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);
});