Validator using asynchronous methods in Angular 2

Currently, I am in the process of incorporating asynchronous custom validation into my project. Below is the structure of my validation class:

export class CustomValidators{
_auth_service;
constructor(auth_service:AuthService){
    this._auth_service = auth_service;
}

usernameTaken(control: Control) {
    console.log(this._auth_service);
    let q = new Promise<ValidationResult>((resolve, reject) => {
    this._auth_service.emailtaken('email='+control.value).subscribe(data=>{
            var result = data.json().result;
            console.log(result);
            if(result===true){
                resolve({"usernameTaken": data});
            }else{
                resolve(null);
            }
        });
});
return q;
}

}

Upon further examination, in my component:

this.customValidators = new CustomValidators(this._auth_service);

I then proceed to integrate it into the form control like this:

this.emailControl = new Control('',Validators.compose([Validators.required, Validators.pattern(ConfigService.EMAIL_REGEX)]),this.customValidators.usernameTaken); 

In this implementation, I have attempted to inject a service into my validator. However, upon testing, I observed that the this._auth_service property within my validator method returns undefined, although it was properly initialized in the validator's constructor.

My intention is to avoid utilizing the validator as a directive, even though it simplifies the process of injecting services. Any ideas on what might be causing this issue?

Answer №1

It seems that there is a missing context here. To properly bind the validator method to the validator instance object, make sure to do it explicitly:

this.usernameControl = new Control('', Validators.compose([
  Validators.required, 
  Validators.pattern(ConfigService.USERNAME_REGEX)
 ]), this.customValidators.checkUsernameAvailability.bind(this.customValidators));

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 is unable to start the variable_INITIALIZation process

I've created a method called get that returns data of type ProductModel. getProduct(id:number): Observable<ProductModel[]> { const url = `${'api/product/getProductById/'}/${id}`; return this.http.get<ProductModel[]>(u ...

Angular 2: Capturing scroll events from the parent element within a Directive

One of the challenges I encountered is with a directive called [appInvalidField] that functions like a custom tooltip for validation purposes. To ensure it appears above everything else within dialogs, I attach it to the body and position it near the relev ...

Removing item from Angular service

Within my Angular 2 application, I have created a service called events.service.ts: const EVENTS = { 1512205360: { event: 'foo' }, 1511208360: { event: 'bar' } } @Injectable() export class EventsService { getEvents() ...

What is the best way to prevent the hassle of manually reloading a VS Code extension each time I make updates

While working on my VS Code extension, I keep encountering the issue of opening a new instance of VS Code every time I run the extension to view recent changes. This becomes especially tedious when using VS Code remote and having to enter my password twice ...

Tips for configuring the cookie expiration date using the ngx-cookie-service library

Can anyone offer assistance with setting the expire date for cookies in my Angular 5 app using ngx-cookie-service? Here is what I have tried: setCookies($event){ this.cookieService.set( 'retailAppCookies', "true", 30 ); this.cook ...

Deciphering Route Parameters within Angular 2

Recently diving into Angular 2, I stumbled upon this resource, which details various methods for creating route links. 1. <a [routerLink]="[ '/path', routeParam ]"> 2. <a [routerLink]="[ '/path', { matrixParam: 'value&ap ...

Simulated database in a Service using TypeScript with Node

Struggling with a unit test, I need to mock the this.orderRepository.findById(id); method to find an object by its ID. Although I've set the return value, the test keeps failing. This is my first time creating a unit test in Node using TypeScript and ...

Executing a PHP function within a Laravel controller using Ajax

In my Laravel project, I have a Controller named Clientecontroller that is working perfectly. It contains a method called listar() which retrieves client information. public function listar(Cliente $cliente) { $clientes = DB::table('clientes' ...

Encountering the "Not all code paths return a value" TypeScript error when attempting to manipulate a response before returning it, however, returning the response directly works without any issues

Encountering an issue where manipulating/process response and return triggers an error in TypeScript with the message "Not all code paths return a value.". Data is fetched from a backend API using RxJS lastValueFrom operator, along with lodash functions as ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...

Unable to modify data with ionic and firebase in child node format

I am encountering an issue when updating data with Ionic Firebase using the following code. Instead of rewriting the previous data, it simply creates new data entries. Here is the code snippet: updateLaporan() { this.id =this.fire.auth.cur ...

What is the best way to transform a synchronous function call into an observable?

Is there a conventional method or developer in RxJS 6 library that can transform a function call into an observable, as shown below? const liftFun = fun => { try { return of(fun()) } catch (err) { return throwError(err) } ...

The process of transferring a list of objects to another in Typescript

There seems to be an issue with copying values from "all" to "available" and sometimes not getting the value from "available" as well. I've tried multiple methods like using slice(), Array.from(), and simply assigning with =, but none of them seem to ...

The module './$types' or its related type declarations could not be located in server.ts

Issue with locating RequestHandler in +server.ts file despite various troubleshooting attempts (recreating file, restarting servers, running svelte-check) +server.ts development code: import type { RequestHandler } from './$types' /** @type {imp ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

Accessing Facebook in Ionic 2 Release Candidate 0

I'm interested in adding a Facebook login feature to my Ionic 2 app, but I'm unsure of how to proceed. Most tutorials I've come across demonstrate how to do this with Firebase database, while my project is already using MySql. Can someone gu ...

Leverage Angular2 components within Angular4 framework

Would it be possible to utilize angular2 components in angular4 projects? Specifically, I am interested in using a chart generation library from . However, it seems that the dependencies of this library are not compatible with my application. Are angular2 ...

Exploring Attack on Titan alongside the concept of dynamic route templates in coding

I am currently working on creating a factory for an UrlMatcher. export const dummyMatcher: UrlMatcher = matchUrlFn(sitemap as any, 'dummy'); export const routes: Routes = [ { matcher: dummyMatcher, component: DummyComponent }, { path: &apos ...

Modify the color of the designated Tab in the PRIMENG TabMenu - customize the style

Currently, I am utilizing the Primeng tab menu component and facing an issue. Unfortunately, I seem to be unable to identify a method to alter the color of the selected tab to a different shade. If anyone has any insights or suggestions on how to achieve ...

Exploring the integration of multiple HTTP requests in Angular with the power of RxJS

Is there a way to make multiple HTTP calls simultaneously in an Angular service and then combine the responses into one object using RxJS? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; im ...