Why this Angular 4 custom validator return a Promise or an Observable? What is the exact logic?

292 views Asked by At

I am very new in Angular 4 and I am not so into JavaScript\TypeScript and I have the following doubt about this example found in a tutorial.

It is related to the implementation of a custom form validator but my doubts are more about the Observable and Promise objects.

So I have something like this:

import {Form, FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';

export class CustomValidators {
  static asyncInvalidProjectName(control: FormControl): Promise<any> | Observable<any> {
    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        if (control.value === 'Testproject') {
          resolve({'invalidProjectName': true});
        } else {
          resolve(null);
        }
      }, 2000);
    })
    return promise;
  }
}

The asyncInvalidProjectName() method implements the logic of my custom validator.

My doubts are:

1) It seems to me that this method can return a Promise object OR an Observable object.

Why? It seems to me that it always return a Promise object that represents if the input in the form is valid or not. Why in the signature it seems that can return also an Observable?

2) What exactly represents a Promise object and what are the difference with an Observable? (from what I know an Observable is used to react to event change)

0

There are 0 answers