验证程序返回的值不正确

时间:2018-12-18 17:51:37

标签: angular

我在验证器中显示正确的值时遇到问题。我的验证器在输入表单字段后检查数据库中是否已存在给定的“用户名”。

现在,它无法正常工作。例如:数据库中存在用户名-> abc,返回错误值:“用户名可用!”并返回到不存在的值“已使用UserNamme!”。

我的后端响应返回正确的值(如果存在,则返回true;否则,返回false)。我认为问题出在Angular的自定义验证器中。

我提供的服务:

  TakeUsernameIfExist(username): Promise<boolean> {
      return this.http.get<boolean>(this.rootUrl + '/api/TakeUserName/' + username ).toPromise();  
}

注册组件:

export class RegisterComponent implements OnInit {

  form: FormGroup;
  constructor(private formBuilder: FormBuilder, private userService: UserService, private router: Router) { }

  ngOnInit() {
    this.formInitBuilder();
  }

  formInitBuilder() {
    this.form = this.formBuilder.group ({
      UserName: new FormControl('', [Validators.required], this.validateUserNameTaken.bind(this)),
      Password: new FormControl('', [ Validators.required, Validators.minLength(3)]),
      Email: new FormControl('', [Validators.required, Validators.email]),
      FirstName: new FormControl(),
      LastName: new FormControl()
    });

}
// Validator
validateUserNameTaken(control: AbstractControl) {
  return this.userService.TakeUsernameIfExist(control.value).then(res => {
    return res ? null : { userName : true };
  });

}
onSubmit(form: FormGroup) {
  if (form.valid) {
  this.userService.registerUser(form.value).
   subscribe((data: any) => {
      if (data.Succeeded === true) {
        this.router.navigate(['/login']);
     }
    });
  } else {
    console.log('error');
  }
}
}`

HTML模板:

<form class="main-form needs-validation"  [formGroup]="form"  >
  <div class="row">
    <div class="col">
      <div class="form-group">
        <input  type="text" class="form-control" name="UserName" formControlName="UserName" required>
        <div *ngIf="form.get('UserName').status === 'PENDING'">
          Checking...
        </div>
        <div *ngIf="form.get('UserName').status === 'VALID'">
           UserName is available!
        </div>
        <div *ngIf="form.get('UserName').errors && form.get('UserName').errors['userName']">
          UserNamme is taken!
        </div>
      </div>
    </div>
  </form>

和Wep API:

        [HttpGet]
        [AllowAnonymous]
        [Route("api/TakeUserName/{username}")]
        public async Task<IHttpActionResult> TakeUserName(string username) 
        {
            var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
            var manager = new UserManager<ApplicationUser>(userStore);

            var result = await  userStore.FindByNameAsync(username);
          return (result == null )  ? Ok(false) : Ok( !string.IsNullOrEmpty(result.UserName));

        }

欢迎任何帮助或建议。

0 个答案:

没有答案