Angular 2/4 throws an Error when a Promise is rejected

I implemented an asynchronous validator function as shown below.

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

An error is being thrown, possibly related to the reject method.

Cannot read property 'ngOriginalError' of null

Any suggestions on how to fix this error would be greatly appreciated. Thank you.

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

Answer №1

It is advisable to reject a Promise with an Error rather than just rejecting it in general.

reject(new Error('User is not named vikash (provide a descriptive message explaining what went wrong)'));

UPDATE When implementing an async validator, make sure to resolve a Promise with null instead of rejecting it to indicate successful validation.

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);
    });
}

Check out the demo here

Answer №2

When it comes to angular form validation, passing null when the field is valid may seem a bit confusing at first. However, that's how it works. For more information, you can refer to this link and this one.

Here is a Plunker link that I have forked from your work. I have made a slight change where null will be returned for valid fields, and ValidationErrors for invalid ones. Additionally, I have included the errors object of the field in the HTML for clearer validation status.

https://embed.plnkr.co/t0gniM/

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      Please open developer console to check the exception <br>
      Type anything and click anywhere other than the textbox<br><br>

      <form [formGroup]="formObj">
      <input type="text" id="username" formControlName="username" placeholder="Username" />
      {{formObj.controls['username'].errors|json}}

      </form>
    </div>
  `,
})
export class App {
  name:string;
  shouldBeUnique(control:AbstractControl):Promise<ValidationErrors|null>{
    return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (control.value === 'vikash') {
                  console.log('---matched--');
                    resolve(null);
                }else{
                resolve({ shouldBeUnique: true });
                }
            }, 1000);
        });
  }

  formObj = new FormGroup({
    username: new FormControl('', [
      Validators.required
    ], [
      this.shouldBeUnique
      ])
  });
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

}

@NgModule({
  imports: [ BrowserModule,FormsModule,ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

I hope this explanation helps clarify things for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When transferring the code to the src folder, tRPC encounters issues and stops functioning

Currently, I am working on developing a basic Twitter clone using Next and TRPC. While tRPC is up and running smoothly, I am looking to streamline my code by consolidating it all within the src directory. However, upon moving everything, I encountered an i ...

Issue with the exported elements known as 'StatSyncFn'

My build is showing an error that I'm unable to identify the source or reason for. The error message looks like this... Error: node_modules/webpack-dev-middleware/types/index.d.ts:204:27 - error TS2694: Namespace '"fs"' has no expo ...

Cosmic - Ways to incorporate personalized validation strategies into the `getConfigValue()` function?

Why is the getConfigValue() function not retrieving validation values from custom Strategies? For example: @Injectable() export class CustomStrategy extends NbPasswordAuthStrategy { protected defaultOptions: CustomStrategyOptions = CustomStrategyOptio ...

Jest encountering errors when compiling a generic function

I'm able to successfully run my Node app, but running tests on a class with Generics is causing an error. The test code looks like this: import { Request, Response } from 'express'; import { JsonWebTokenError } from 'jsonwebtoken' ...

The seamless pairing of Cucumber and Playwright: Cucumber's inability to retain cookies results in a login attempt with every scenario

I am currently facing an issue with integrating cucumber and playwright into my framework. When attempting to execute various features or multiple scenarios within one feature, I encounter a problem where if one scenario logs into a site, the other scenari ...

Using a for loop in conjunction with Observable.forkJoin

In my component, I am striving to populate an array known as processes, containing individual process objects that each have a list of tasks. Currently, I am dealing with two API calls: /processes and /process/{processId}/tasks I utilize the /processes ...

Issue encountered during ng2-redux installation

While attempting to use the https://www.npmjs.com/package/ng2-redux link, I encountered an issue when running npm install redux ng2-redux --save. Here is the stacktrace of the error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files& ...

Angular is able to successfully retrieve the current route when it is defined, but

Here's the code snippet I am working with: import { Router } from '@angular/router'; Following that, in my constructor: constructor(router: Router) { console.log(this.router.url); } Upon loading the page, it initially shows the URL a ...

What benefits does using the --output-hashing=all command bring to an Angular build process?

During production build, a command is used as: ng build --aot --output-hashing=all --prod --base-href "/xyz/" --deploy-url "/xyz/" Can you explain the purpose of --output-hashing=all in this command? ...

Navigate to a different route in AntD Table by clicking on it

I am currently implementing React Router in my navigation component. My goal is to enable users to navigate from screen Y to screen X when they click on a table element. In the past, I achieved this by using "this" command but it seems that it does not ...

How can I access the component name and parameters during the NavigationEnd event?

We are currently setting up Google Analytics and we want to track the URL, parameters, and components in GA. this.router.events .pipe( filter(event => event instanceof NavigationEnd) ) .subscribe((event: NavigationEnd) => ...

Divide Angular module

In my Angular application, I have set up pages with a consistent header and sidebar structure. However, the main content on these pages may change based on different routes. To keep things organized, I decided to create a central page outlet where the main ...

Error in typography - createStyles - 'Style<Theme, StyleProps, "root"

I'm encountering an error in a small React app. Here is a screenshot of the issue: The project uses "@material-ui/core": "4.11.3". In the codebase, there is a component named Text.tsx with its corresponding styles defined in Text.styles.tsx. The styl ...

Transforming a JavaScript component based on classes into a TypeScript component by employing dynamic prop destructuring

My current setup involves a class based component that looks like this class ArInput extends React.Component { render() { const { shadowless, success, error } = this.props; const inputStyles = [ styles.input, !shadowless && s ...

What is the reason behind Typescript's discomfort with utilizing a basic object as an interface containing exclusively optional properties?

Trying to create a mock for uirouter's StateService has been a bit challenging for me. This is what I have attempted: beforeEach(() => { stateService = jasmine.createSpyObj('StateService', ['go']) as StateService; } ... it(& ...

Can metadata be attached to data models in Angular for annotation purposes?

Looking to add some metadata annotations to a simple data model export class Certification { title: string; certificationType?: CertificationType; validTo?: number; description?: string; externalIdentifier: Guid; constructor() { ...

What is the datatype for an Angular FormControl when dealing with numbers?

Having an issue with Angular FormControl when using it for text and number inputs. Both inputs are being recorded as text even though one is supposed to be a number. var control = this._formBuilder.control(this.settings[input.property]); control.valueChan ...

What are the recommended techniques for utilizing prototypal and prototype-based inheritance in modern JavaScript (ES6) and TypeScript?

Some older discussions on Javascript prototypal inheritance & delegation can be found below: Benefits of prototypal inheritance over classical? classical inheritance vs prototypal inheritance in javascript I am curious about the current (2018) recom ...

Ending the Infinite Scroll in Ionic 3 When Data Runs Out

I am having an issue with my json data where I need to figure out how to stop the infinite scroll once there is no more data available. Can anyone help me implement this feature? Below is the code snippet for reference: handleDataLoad(currentCount) ...

Angular ng-bootstrap modal dialog: retrieving closeResult value before proceeding with execution

I've been working on an Angular project using ng-bootstrap (currently version 5), and I've successfully implemented a modal component that can be called from multiple components with unique title and message inputs. However, I'm encounterin ...