首页 > 解决方案 > 在 Angular 8 中进行同步调用

问题描述

我有一个要验证的输入字段。

我正在使用自定义验证器来检查该输入字段值的有效性。

在自定义验证器中,我正在使用输入字段值对端点进行休息调用,以检查输入的值是否有效。

问题是在从其余 API 返回验证结果时,httpClient get 调用以异步方式工作。输入字段验证器出现并且验证无法按预期工作。

有没有办法同步进行http调用。

我在自定义验证器中的 httpClient 调用代码:

labelNameValidators.ts:

import {FormControl } from '@angular/forms';

export function labelNameValidators(control: FormControl) {

  if(control.value!=null) {
    this.labelService.checklabelNameFormat(control.value)
    .subscribe(
      (data) => {

        if (data === 'true') {
          console.log('success', data);
          return  {'labelMsg': { 'message' : data}};
        }
        else {
          console.log('failure', data);
          return  {'labelMsg': { 'message' : data}};
        }
      },
      (err) => {
        console.log('error', err);
        return null;
      }
    )
  }
}

标签.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})

export class LabelService {

private nameFormatCheckApi = environment.nameFormatCheckApi;

  constructor( private http: HttpClient ) { }

  checklabelNameFormat(name: string){
    return this.http.get(this.nameFormatCheckApi + '?name='+name);
  }
}

标签: angulartypescriptangular8

解决方案


您可以为您的案例使用异步验证器。

this.form = new FormGroup({
      fieldExample: new FormControl(
        null, Validators.required, asyncValidator())
});

在这里,您是一个使用带有模板驱动表单和响应式表单的异步验证器的现场演示。

https://stackblitz.com/angular/bbdorarjxea


推荐阅读