Vikash Verma Vikash Verma - 30 days ago 14
TypeScript Question

Promise's reject is throwing Error in angular 2/4

I have defined a async validator function like this.

static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === 'some_text') {
resolve({ shouldBeUnique: true });
}
reject(null);
}, 2000);
});
}


Its throwing below error (may be on reject)


Cannot read property 'ngOriginalError' of null


How to get rid of this error?
Thanks

Plnkr : https://embed.plnkr.co/VSHXGKiMGUWEhy8neyXU/

Answer Source

Reject with an Error

reject(new Error('User is not vikash (whatever descriptive message what went wrong)'));

EDIT Since you are trying to implement async validator you need to resolve a Promise with null not to reject it to indicate validation was ok.

static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (control.value === 'some_text') {
              resolve({ shouldBeUnique: true });
            } else {
              resolve(null); // resolve
            }
        }, 2000);
    });
}

Demo