大家晚上好。我想知道如何在Angular 2/4打字稿中的Promise then()
中访问外部变量。我正在尝试通过Rest API完成动态表单验证以检查用户名可用性。
这里userService.isUsernameAvailable(userName)
返回一个完美无缺的承诺。我唯一想要回答的是,如何更改i
和then()
上的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
}
}
提前谢谢大家。
答案 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