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

What are some solutions to the error message "Error: Cannot find any matching routes" that appears when trying to switch between tabs following a successful login?

I am facing an issue with my Ionic 4 (4.10.2 with Angular 7.3.1) app where I want to make it accessible only after login. Following a tutorial from , I encountered a problem when trying to access the ion-tabs section of my app. Chrome keeps showing this er ...

Are child routes permitted to be utilized without the need for router outlets, specifically for tab contents within a main component?

Can different components be rendered for each tab in a tab menu without using router outlets? Within my parent component, there is a template containing a tab menu component with each tab item having an ng template associated with it. I have set the tabs p ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

What causes the error message saying 'undefined' cannot be assigned to the specified type ...?

I just finished developing an innovative Angular application. Within the app.component.html file, I have included: <bryntum-scheduler #scheduler [resources] = "resources" [events] = "events" [columns] = "schedul ...

Securing Angular 2 routes with Firebase authentication using AuthGuard

Attempting to create an AuthGuard for Angular 2 routes with Firebase Auth integration. This is the implementation of the AuthGuard Service: import { Injectable } from '@angular/core'; import { CanActivate, Router, Activated ...

Unable to compile an Ionic 5 (angular) application with Node.js versions 12.22.12 or 12.22.6

I'm facing a challenge with an old app that requires me to run it using nvm for compatibility with older versions of node.js and ionic. Despite the outdated dependencies, I simply need to get it running in a development environment. Upon attempting t ...

What is the rationale behind Angular's decision to use cdr.markForCheck() instead of cdr.detectChanges() in the async

Regarding Angular, I have a question: Why does the Angular async pipe use cdr.markForCheck() instead of cdr.detectChanges()? I have noticed two main differences between these two approaches: markForCheck() marks the path all the way up to the root compo ...

Exploring the zorro components (nz-tree) in Angular for effective testing with Jasmine and Karma

How can I access the data in the $event and verify if the treeClick method is being called upon click? When running the test file, I encountered the following error: "Expected spy treeClick to have been called once. It was called 0 times." In t ...

Inheriting Components from Templates

Insight on Motivation There are countless situations where we may require multiple components to share the same functionalities. It is not ideal (and definitely shouldn't be done!) to simply copy child components. This is where the concept of inherit ...

having trouble retrieving information from mongodb

Currently working with nestjs and trying to retrieve data from a collection based on the 'name' value. However, the output I am getting looks like this: https://i.stack.imgur.com/q5Vow.png Here is the service code: async findByName(name):Promi ...

"Encountering a blank page in React Router when transitioning between separate projects

I've come across some discussions about a similar issue like this one, but I haven't been able to resolve my problem. In my initial project, I can smoothly navigate between its pages. However, when I created a second project hosted in a subdirec ...

What is the process for running an Angular 1.4 application on a system with Angular 6 installed?

After installing Angular 6 with CLI, I realized that my project was written in Angular 1.4. How do I go about running it? ...

Having issues with Angular jasmine 2 $q promise failing to trigger .then function

Confusion has overtaken me as I try to make sense of the situation at hand and find a solution. My focus is on testing this particular code snippet, but for some reason, .then never seems to get called: describe('PicturesSvc.updatePicturesList', ...

Troubleshooting the error of an undefined RouterModule

Working on implementing lazy loading for my Angular 4 application, I have a total of 18 lazy loaded modules. Upon noticing that fetching these modules is taking some time, I decided to add a loading indicator. Everything worked fine when I added it locally ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

Step-by-step guide on implementing Form.create in TypeScript and Ant Design with function components

Having trouble compiling my form created using Form.create(). The error message I'm getting is: Argument of type 'FunctionComponent<MyProps>' is not assignable to parameter of type 'ComponentType<{}>'. Type 'Fu ...

Tips on applying borders to dynamically generated content in jspdf autotable, similar to a template

Having trouble adding borders to my PDF generated using jsPDF autotable. I want the layout to match the template, can someone assist me in resolving this issue? I need the header border to consist of two lines, similar to the template image provided below ...

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

Can we rely on the security of Ionic 4 secure storage encryption?

I'm currently developing an application that necessitates the user to be in close proximity to a specific GPS location. At present, I am obtaining their location every 30 seconds, transmitting it to my server, checking if they are near the desired loc ...

Change prompt-sync from require to import syntax

In my Node project, I have integrated the prompt-sync module. const prompt = require('prompt-sync')(); const result = prompt(message); To maintain consistency in my TypeScript code, I decided to switch from using require to import. In order to ...