【问题标题】:Multiple API calls being made when using Async Form Control Validation Angular 2使用异步表单控件验证 Angular 2 时进行多个 API 调用
【发布时间】:2017-03-10 20:52:49
【问题描述】:

我正在尝试通过 FormControl 添加异步验证,并且每次按键都会收到多个响应。每次我从表单控件中键入/删除一个字符时,都会发出一个额外的请求。

basics.component.ts

export class TrainingModuleBasicsComponent implements OnInit, StepperItem<TrainingModule>  {
  trainingModule: FormGroup;
  errorMessages: Object;
  formErrors: Object;
  model: TrainingModule;

  constructor(private fb: FormBuilder, private trainingModuleService: TrainingModuleService) { }

  ngOnInit() {
    this.buildForm();
    this.buildValidation();
  }

  buildForm(): void {
    const codeRegex = '[a-zA-Z0-9-_]*';

    this.trainingModule = this.fb.group({
      moduleCode: [this.model.moduleCode, Validators.pattern(codeRegex), [this.validateDuplicateCourseCode.bind(this)]],
      title: [this.model.title, Validators.required],
      description: [this.model.description]
    });
  }

  private validateDuplicateCourseCode(control: AbstractControl) {
    return new Observable((obs: any) => {
      control.valueChanges
                 .debounceTime(400)
                 .distinctUntilChanged()
                 .switchMap(value => this.trainingModuleService.verifyCourseCode(value))
                 .subscribe(
                   data => {
                     console.log('request made');
                     if (!data.error) {
                       obs.next({'duplicateCourseCode': true});
                       obs.complete();
                     } else {
                       obs.next(null);
                       obs.complete();
                     }
                   }
                 );
    });
}

training-module.service.ts

@Injectable()
export class TrainingModuleService {

  constructor(private http: Http) { }

  verifyCourseCode(courseCode: string): Observable<any> {
      return this.http.get(environment.rlmsApi + '/Modules/Code/' + courseCode,
                            new RequestOptions({ headers: new RlmsHeaders() })
                        )
                      .map(res => Observable.of(res.json()))
                      .catch(e => Observable.of(e.json()));
  }

【问题讨论】:

  • 你的问题是什么
  • validateDuplicateCourseCode 函数在第一次按键时调用 3 次。再按一次按键后,该函数会进行 4 次调用。在另一次按键之后,它会拨打 5 次电话,并以这种方式继续。如果用户在按键后暂停(debounceTime),我只希望它每次按键发出一个请求。相反,似乎直到 debounceTime 之后才进行调用,但它们都是在之后调用的。
  • @JosephWilliams 你是怎么解决这个问题的?我实际上有一个类似的问题。当我的表单显示多个调用时。

标签: javascript angular rxjs observable


【解决方案1】:

我认为问题在于您订阅了control.valueChanges

我想这就是你想要的。:

private validateDuplicateCourseCode(control: AbstractControl) {
    return new Observable((obs: any) => {
        this.trainingModuleService.verifyCourseCode(control.value)).subscribe(data => {
             console.log('request made');
             if (!data.error) {
                 obs.next({'duplicateCourseCode': true});
                 obs.complete();
             } else {
                 obs.next(null);
                 obs.complete();
             }
         }
     });
});

【讨论】:

  • 到目前为止运气好吗?
猜你喜欢
  • 2017-03-02
  • 2019-02-08
  • 2017-08-07
  • 2018-06-17
  • 2017-08-08
  • 2017-10-06
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
相关资源
最近更新 更多