首页 > 解决方案 > 在 Angular 中使用 async/await 函数时出现问题

问题描述

早上好,

即使在阅读了 and 的概念和用途之后asyncawait我仍然对它们的实际应用有疑问。

基本上在我的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;

   }

问题是currentUsernull在执行时返回,因为它的值是在从承诺返回之前设置的this.auth.getSession(this.token);

Auth是在一个名为的服务中构建的RestApiService

constructor(private auth: RestApiService) { }

此外,我在该服务内部有一个方法getSession(),该方法JSONAPI

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

我试过把getSessionasasync和它的调用放在一起,像这样:

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

标签: javascriptangulartypescriptasynchronous

解决方案


尽管您的getSession方法尝试执行异步操作,但您尚未将其设置为正确执行此操作。你在块currentUser之外返回subscribe,整个方法无法告诉它的调用者它是异步的,所以 async/await 不会有什么不同。

当涉及到异步方法时,您有几个选择。在 Angular 中,我们通常使用 Observables,因为它们允许最多的控制。在这种情况下,您可以简单地在 中返回http.postObservable getSession,然后在 中订阅它authenticateUser。然后,您可以将以下几行放入subscribe调用中,或者使用pipeRxJS 运算符来执行下一步操作。

您还可以getSession返回一个Promise用所需数据解析的。这将允许 async/await 工作(尽管它不是 Angular 模式)。


推荐阅读