在Angular Promise then()函数中访问外部变量

时间:2017-08-05 22:01:23

标签: javascript angular typescript angular-promise

大家晚上好。我想知道如何在Angular 2/4打字稿中的Promise then()中访问外部变量。我正在尝试通过Rest API完成动态表单验证以检查用户名可用性。

这里userService.isUsernameAvailable(userName)返回一个完美无缺的承诺。我唯一想要回答的是,如何更改ithen()上的catch()值。

static usernameAvailabilityValidator(userService: UserService) {
      let i = 1; //outer variable
      userService.isUsernameAvailable(userName).then((res) => {
        i = 2;
      }).catch((res) => {
        i = 3;
      });
      console.log("i is "+ i); // should output 2 or 3
  }

IRRELEVANT BELW

以下与此问题无关:我在下面添加代码,为我尝试实现的目标提供背景信息。你不必阅读它,它不会添加到我的问题中。

我的目标是返回一个为验证器返回null或JSON对象的函数,因为验证器在Angular 2中的工作方式。

static usernameAvailabilityValidator(userService: UserService) {
    return (control: FormControl) : any =>{
      let userName: string = control.value;
      console.log("current username"+userName);
      let i = 1;
      let response:{} = null; //here response is similar to i
      userService.isUsernameAvailable(userName).then((res) => {
        i++;
        if (res.status == 1) {
          response = null;
        }
        else {
          response = {'usernameInUse': 1};
        }

      }).catch((res) => {
        response = null;
      });
      console.log("i"+i);
      return response; // response is returned to the outside function
    }
  }

提前谢谢大家。

2 个答案:

答案 0 :(得分:0)

isUsernameAvailable返回一个Promise,因为它在被调用后不能立即返回一个值(因为它等待网络请求)。因此,console.log("i"+i);return response;会在then回调之前和变量修改之前被调用。因此,usernameAvailabilityValidator无法立即返回值,您可以返回Promise或使用TypeScript的async / await功能(https://basarat.gitbooks.io/typescript/content/docs/async-await.html)。

答案 1 :(得分:0)

您需要为同一个

实现异步验证器

例如 -

validate(c:AbstractControl) {
    return new Promise(resolve =>
      this.accountService.getUserNames(c.value).subscribe(res => {
        if (res == true) {
            resolve(null);
        }
        else {
            resolve({validateEmailTaken: {valid: false}});
        }
    }));
  }

您可以在此Reactive&上找到有关验证者的更多信息。 TemplateDriven