0

I'm trying to create a custom validator for Slug form control. Here is my code.

ngOnInit() {
    this.slugCtrl.setAsyncValidators(this.slugValidator);
}

slugValidator(control: AbstractControl) {
    const obs1 = control.valueChanges.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      map(val => {
        this.isError = of(false);
        if (val === ' ') {
          this.isAvailable = of(false);
          // this.slugCtrl.setErrors({ required: true });
          return { required: true };
          // obs.next({ required: true });
          // obs.complete();
        }
        this.isAvailable = of(false);
        if (this.slugCtrl.valid) {
          this.store.dispatch(new SlugActions.checkSlug({ slug: val }));
        }

        console.log(val);
      })
    );

    return obs1;
}

When ever the validator runs it says that can not read property isError of undefined. It means that "this" is not being passed in map function. What am I doing wrong here?

Also, How can I return multiple observables? Because my slug validation has many things to check from different resources and each resource returns an observable. Here is further code

   this.store.select(getSlugsIsProcessingFail()).subscribe(data => {
    this.store.select(getSlugsIsProcessingError()).subscribe(_err => {
      if (_err === 'Server error') {
        alert(
          'There was an error processing your request. Please try again!'
        );
        this.isError = of(false);
      } else if (_err.hasOwnProperty('message')) {
        this.error = _err.message;
        // this.slugCtrl.setErrors({ available: true });

        this.isError = of(true);
        return { required: true };

      }
    });
    this.store.select(getSlugsIsProcessingSuccess()).subscribe(data => {
      if (data) {
        this.isAvailable = of(true);
        // this.slugCtrl.setErrors(null);
         return null;

      }
    });
  });
Shahrukh Shahid
  • 418
  • 4
  • 16
  • 3
    Try defining the validator as an arrow function: `slugValidator = (control: AbstractControl) => { ... }`. Or set it with the syntax: `this.slugCtrl.setAsyncValidators(this.slugValidator.bind(this));`. – ConnorsFan Aug 27 '18 at 14:46

1 Answers1

2

You should use arrow functions to bind this with your function

slugValidator = (control: AbstractControl) => {
...

}
Dinosan0908
  • 1,082
  • 2
  • 8
  • 19