【发布时间】:2014-02-26 21:05:37
【问题描述】:
在我的 AngularJS 应用程序中,每次请求更改我运行的页面:
$rootScope.$on('$locationChangeStart', function (event, next, current) {
var user;
$http.get('/api/Authentication/UserAuthenticated').then(function (data) {
console.log("call");
user = data.data;
});
console.log("end of call");
});
当我运行应用程序并测试正在发生的事情时,我在控制台中看到“通话结束”在console.log("call"); 之前返回,这意味着未设置用户。这意味着如果我想检查用户是否在更改路由时登录用户将是未定义的。
我如何让 Angular 运行-> http 请求,然后才能继续?
【问题讨论】:
-
这与
promises无关,而是$http进行异步调用。由于get调用是异步的,所以"end of call"总是首先出现。 -
对于此类任务,您应该使用路由配置的
resolve属性。 -
你能举个例子说明我如何用resolve实现它吗?我可以看到我解决的文档会让 rute 等到所有 http 请求都完成
-
请查看我的回答。