Implementing asynchronous validation in Angular 2

Recently started working with Angular 2 and encountered an issue while trying to validate an email address from the server

This is the form structure I have implemented:

this.userform = this._formbuilder.group({
  email: ['', [Validators.required], [this._validationService.emailExistsValidator.bind(this)]],
});

The _ValidationService I am using:

@Injectable()
export class ValidationService{

  constructor(
    private _authService:AuthService
  ){}

  emailExistsValidator(control) {
    if (control.value != undefined) {
      return     this._authService.checkExists("email")
        .map(response => {
          if (!response) {
            return {'emailNotExists': true};
          }
        });
     }
   }
}

And in the AuthService:

@Injectable()
export class AuthService {

  checkExists(value):Observable<any>{
    return this._http.get(this.authurl+value)
      .map(response => {
        return response  //this is either true or false
      });
   }

}

I tried setting up the form validation based on guidance from This source but it is not working as expected

An error message that I receive is:

Cannot read property 'checkExists' of undefined
at UsersComponent.webpackJsonp.187.
 ValidationService.emailExistsValidator

Seeking help to understand what could be causing this issue

Answer №1

When it comes to pointing this towards the ValidationService, the call for bind() is crucial:

this.formGroup = this._formbuilder.group({
  email: ['', [Validators.required], [this._validationService.emailExistsValidator.bind(this._validationService)]],
});

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

Angular 2+ seems to be failing to detect and update changes in variables within the template

I have a component that includes rendering the user's name from the profile object. The corresponding part of the template looks like this: <button mat-button [matMenuTriggerFor]="userMenu" *ngIf="isAuthenticated()"> {{profile?.name} ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

Having difficulty authenticating Slack requests

I'm currently working on a project to develop a Slack bot using the events API for an experiment at my job. I am facing challenges in verifying the request and can't seem to pinpoint where I'm making a mistake. The bot is being built using ...

What is the best method in JavaScript to create three different shades of a color?

My sass function generates lighter and darker versions of a base color, here is the code snippet: $colors: ( betpawa-green: #107A3D, lime-green: #8DC63F, yellow: #FBCD00, ); @mixin color-generator { @each $name, $hex in $colors { &-#{$nam ...

An error occurred: an unexpected identifier was found when trying to import axios using './lib/axios.js' and require('axios')

I am currently working with a js file: test.js: const axios = require('axios'); console.log('test'); To set up the dependencies, I ran the command npm install This is how my folder structure is organized: test node_modules packa ...

Tips for attaching a "progress" and refresh event to an ajax call while sending a file

I am currently using the FormData API and AJAX to upload files to a server in PHP-CodeIgniter. The file upload works perfectly when triggered by the file select event. However, I would like to display a progress bar next to each file being uploaded with th ...

Utilizing jQuery to dynamically convert a dropdown into a multiselect when triggered by the selection of another dropdown within a form containing cloned

After coming across discussions on using a multiselect based on another multiselect, cloning a form row, and dynamically updating select options, it seems there are no answers detailing how to combine all three concepts together. In my particular scenario ...

Is there another way to implement this method without having to convert snapshotChanges() into a promise?

When trying to retrieve cartIdFire, it is returning as undefined since the snapshot method is returning an observable. Is there a way to get cartIdFire without converting the snapshot method into a promise? Any workaround for this situation? private asyn ...

Update the input for a component within the ngOnChanges method, and ensure that the OnPush change

I've encountered an issue with my Angular 6 application: The Dilemma Imagine I have two components: parent and child. The child component has two inputs. When one input changes, the child emits something to the parent within the ngOnChanges() lifec ...

Reduce the text of the link

Trying to simplify a task, but I'm struggling with the solution. What I want to achieve is shortening a link to 30 characters and adding ... at the end if it's longer. Also, I'd like to make it possible to see the full link on hover similar ...

What is the best method to determine offsetTop in relation to the parent element instead of the top of

I have a straightforward inquiry: How can one determine the offsetTop of a child element in relation to its parent element rather than the top of the window? The definition of offsetTop indicates that it should give the distance by which a child element i ...

Navigate from Product Listing to Product Details Page by utilizing JSON data with ReactJS

I have successfully retrieved the initial level of JSON Data, which consists of objects/Product List. My objective is to implement a functionality where clicking on the "View Details" button will redirect to the respective product detail page, similar to ...

Is it possible to directly parse a multipart/mixed response without needing to first convert it into a string?

My current challenge involves receiving a multipart/mixed response over HTTP that includes JSON data and PDFs in byte format. Due to Angular's limitations with handling such responses, I have resorted to converting the response into a string using the ...

what is the best way to eliminate comments from nested arrays when using useReducer?

Can someone help me figure out how to use useReducer and useContext to manipulate global state? I specifically need to know how to delete comments using useReducer. Data Structures View the interface image here Sample Data Array export const listsData:IDa ...

Experiencing difficulty in adding a sub-document to an array within a parent

I am currently working with a users model that incorporates a locationsSchema: const locationSchema = require('./location.js'); const userSchema = new mongoose.Schema({ email: { type: String, unique: true, required: true, }, t ...

Blogger's homepage URL obtained using JSON data

Please note: I don't have a background in programming. I'm making an effort to learn as much as possible. As I was reading (and later experimenting with) the solution to this query, it dawned on me that having the same information in JSON form ...

The callbackFinished function is not defined in the winwheel library

Every time I attempt to call a function with the callbackFinished property inside the animation of winwheel, I encounter an error stating that the function is not defined, even though it is defined in the same class. import React from 'react' imp ...

Creating a radial progress chart using Plotly JavaScript

I recently started working with the Plotly library and now I need to display a circular progress graph in Vuejs 2, like the one shown below. While Plotly is a comprehensive tool, I have not come across an example that matches this specific design using Ja ...

Tips for converting JSON information on a website and inserting it into a designated division?

I've recently delved into front-end development, searching for solutions and hints without much success. I'm currently in the process of building my first website, specifically a "find recipes" website. Lacking knowledge of API calls, I created a ...

Trouble with Firebase Setup in Ionic 4+ Web Application

I'm currently trying to establish a connection between my ionic application and Firebase for data storage, retrieval, and authentication. Despite using the npm package with npm install firebase, I encountered an error message that reads: > [email& ...