您好我有简单的LoginService,如下所示:
jai_core-1.1.3.jar
这是对服务的调用
this.notifyAuthorization = function() {
console.log('notifyAuthorization()');
$http({
url: 'app/?cmd=authorization/',
}).then(function (response) { console.log('LoginStatusResult: '); console.log(response.data);
var data = response.data;
if(data.hash !== undefined) {
$rootScope.loginStatus= true;
hash = data.hash;
}
});
};
在看到app.run(function($rootScope, $location, LoginService) {
LoginService.notifyAuthorization();
console.log('notifyAuthorization Finished');
});
之前,我看到LoginStatusResult
和其他控制器初始化应该知道LoginStatus所以如何解决这个问题?还是有更好的做法?
感谢
答案 0 :(得分:2)
使用promises,默认情况下由$ http函数提供:
this.notifyAuthorization = function() {
return http({ //notice the return inserted here
url: 'app/?cmd=authorization/',
}).then(function (response) { console.log('LoginStatusResult: '); console.log(response.data);
var data = response.data;
if(data.hash !== undefined) {
$rootScope.loginState = true;
hash = data.hash;
}
});
};
并在app.run中正确使用它:
app.run(function($rootScope, $location, LoginService) {
LoginService.notifyAuthorization().then(function(){
$rootScope.authorized = true;; //executed after your $http request...
});
});
并在您的HTML代码中:
<div ng-controller="myController" ng-if="$root.authorized">
<!-- your inner code..
<p>Pellentesque habitant morbi tristique senectus et netus et
malesuada fames ac turpis egestas. Vestibulum tortor quam,
feugiat vitae, ultricies eget, tempor sit amet, ante. </p>
-->
</div>
这样,只有在.then函数解析后才会实例化控制器