javascript - 在 Angular 中使用 async/await 函数时出现问题
问题描述
早上好,
即使在阅读了 and 的概念和用途之后async
,await
我仍然对它们的实际应用有疑问。
基本上在我的ngOnInit
我调用一个函数:
ngOnInit() {
this.authenticateUser();
}
功能是:
authenticateUser() {
console.log("----Autenticando Usuário----");
this.token = localStorage.getItem("token");
this.userName = localStorage.getItem("userName");
this.userPhoto = localStorage.getItem("userPhoto");
this.currentUser = this.auth.getSession(this.token);
this.attributions = this.currentUser.sessao.grupos;
this.userEmail = this.currentUser.sessao.email;
this.instalation = this.currentUser.instalacao;
}
问题是currentUser
值null
在执行时返回,因为它的值是在从承诺返回之前设置的this.auth.getSession(this.token);
这Auth
是在一个名为的服务中构建的RestApiService
constructor(private auth: RestApiService) { }
此外,我在该服务内部有一个方法getSession()
,该方法JSON
从API
getSession(xtrToken) {
xtrToken = "{\"token\":\"" + xtrToken.toString() + "\"}";
this.http.post(this.apiURL + "/auth", xtrToken)
.subscribe(function (resposta) {
if (resposta != null) {
localStorage.setItem("currentUser", JSON.stringify(resposta));
if (window.location.href.indexOf("?") > -1) {
var url = window.location.href;
var value = url = url.slice(0, url.indexOf('?'));
value = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]', '');
var newUrl = value;
window.history.pushState({}, null, newUrl);
}
this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
}
});
return this.currentUser;
}
我试过把getSession
asasync
和它的调用放在一起,像这样:
async authenticateUser() {
console.log("----Autenticando Usuário----");
this.token = localStorage.getItem("token");
this.userName = localStorage.getItem("userName");
this.userPhoto = localStorage.getItem("userPhoto");
this.currentUser = await this.auth.getSession(this.token);
this.attributions = this.currentUser.sessao.grupos;
this.userEmail = this.currentUser.sessao.email;
this.instalation = this.currentUser.instalacao;
}
但这没有任何区别。
那么,有没有办法API
在我设置值之前等待结果this.currentUser
?
解决方案
尽管您的getSession
方法尝试执行异步操作,但您尚未将其设置为正确执行此操作。你在块currentUser
之外返回subscribe
,整个方法无法告诉它的调用者它是异步的,所以 async/await 不会有什么不同。
当涉及到异步方法时,您有几个选择。在 Angular 中,我们通常使用 Observables,因为它们允许最多的控制。在这种情况下,您可以简单地在 中返回http.post
Observable getSession
,然后在 中订阅它authenticateUser
。然后,您可以将以下几行放入subscribe
调用中,或者使用pipe
RxJS 运算符来执行下一步操作。
您还可以getSession
返回一个Promise
用所需数据解析的。这将允许 async/await 工作(尽管它不是 Angular 模式)。
推荐阅读
- android - onCompeletionListener() 不是每次都调用并且随机播放和重复不能正常工作
- javascript - 浏览器控制台中的 Jest 单元测试模块导出错误
- c - 如果两个任务尝试同时访问结构的不同部分(在 c 中)会发生什么?
- nginx - nginx 将 http 重定向到 https 域
- c# - 如何在c#中对元素进行排名,尤其是当它有重复项时
- c# - 即使有明确的等待,Selenium 也会抛出 NoSuchElementException
- spring - Gradle Spring mvc 验证数据类递归 Kotlin
- python - Eventlet heroku flasksocketio 应用程序不工作
- c# - EF Core 播种用户数据在用户表警告中获得重复角色
- c# - 使用 dotnet 和 MsBuild 构建 .NET 应用程序有什么区别?