Angular 5:Calling service method inside custom validator

user1203497

Basically I have created user service that has getUserByAlias method in it. For testing purpose it doesn't do anything but prints out string. I have been following video tutorial and in tutorial he basically shows that you need to make sure that service is imported, then included in @component, then included in constructor. So my files looks something like this:

create-account.component.ts

import { Component, OnInit, NgModule, Injector, Injectable } from '@angular/core';
import { FormBuilder, FormControl, Validators, FormArray, FormGroup, AbstractControl, ValidatorFn, AsyncValidator, AsyncValidatorFn, ValidationErrors, NG_ASYNC_VALIDATORS } from '@angular/forms';
import { faCheck } from '@fortawesome/free-solid-svg-icons';
import { Observable } from 'rxjs';
import { UserService } from '../user.service';




const passwordValidator: ValidatorFn = (fg: FormGroup): ValidationErrors | null => {
    var pw =  fg.get('password');
    var pw2 =  fg.get('passwordre');
    if(pw2.value.length == 0){
        return null
    }
    if(pw && pw2 && pw.value !== pw2.value){
        pw2.setErrors({'passNoMatch': true});
        pw2.markAsTouched();
        return { 'passNoMatch': true };
    }else{
        pw2.setErrors(null);
        return null;
    }
}

const username: ValidatorFn = (control: FormControl): ValidationErrors | null => {
    var alias = control
    if(alias && /^\w+$/.test(alias.value)==false){//if not only numbers and letters
        return { 'illegalChars': true };
    }else if(alias && /^\d+$/.test(alias.value)==true){//If only numbers
        return { 'onlyNumbers': true };
    }else{
        alias.setErrors(null);
        return null;
    }
}


@Component({
    selector: 'app-create-account',
    templateUrl: './create-account.component.html',
    styleUrls: ['./create-account.component.scss'],
    providers: [UserService]
})

export class CreateAccountComponent{
    faCheck = faCheck
    constructor( private fb: FormBuilder, private userService: UserService) {
        this.userService.getUserByAlias('test') 
    }


    checkUsername(control: FormControl): Promise<any> | Observable<any>{
        this.userService.getUserByAlias(control.value)  
        const promise = new Promise<any>((resolve, reject) =>{
            //const user = new UserService();
            setTimeout(()=>{
                if(control.value === 'test'){
                    resolve({usernameTaken: true})
                }else{
                    resolve(null)
                }
            },1500)
        })

        return promise;
    }


    usernameCtrl =  this.fb.control('', [
        Validators.required,
        Validators.minLength(4),
        username
    ], this.checkUsername)
    emailCtrl =  this.fb.control('', [
        Validators.required,
        Validators.email
    ])
    passwordCtrl =  this.fb.control('', [
        Validators.required,
        Validators.minLength(5)
    ])
    passwordreCtrl =  this.fb.control('', [
        Validators.required,
        Validators.minLength(5)
    ])

    newAccountForm = this.fb.group({
        username: this.usernameCtrl,
        email: this.emailCtrl,
        password: this.passwordCtrl,
        passwordre: this.passwordreCtrl
    },{ validator: passwordValidator})
}

user.service.ts

import { Injectable } from '@angular/core';
@Injectable({
    providedIn: 'root',
})

export class UserService {
    getUserByAlias(alias: any){
        console.log(alias)
        return alias
    }
}

When input triggers checkUsername I get error: ERROR TypeError: Cannot read property 'userService' of undefined. I called this.userService.getUserByAlias('test') inside the constructor and it printed out to console what it needed. So I assumed, that it doesn't work because it has something to do being called inside custom validator. Why doesn't it work inside validator? and how can I make it work?

user184994

The reason is because the context of this is lost.

To remedy this, you can use the bind function, like so:

    usernameCtrl =  this.fb.control('', [
        Validators.required,
        Validators.minLength(4),
        username
    ], this.checkUsername.bind(this));

This will bind the correct context to that function to ensure it works

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

NestJs - Calling a method from a service inside a Custom Decorator

From Dev

Calling a method of same service is not working inside jsPDF, Angular

From Dev

Using Observable inside Custom Validator Angular

From Dev

Angular 5: Using Service from inside Custom Decorator Function

From Dev

Inject a service in a custom validator in Angular2

From Dev

Access service from Custom Validator in Angular

From Dev

method inside service is not function in angular 5 unit tests with karma

From Dev

Angular5 Custom Validator for Date Min

From Dev

GoogleApiClient not calling onConnected method inside service

From Dev

Angular service always undefined when calling in async validator

From Dev

Creating and calling a custom function inside an angular class

From Dev

Angular 1.5: calling a method of a component inside ngRepeat

From Dev

Calling a method inside *ngIf mutliple times angular

From Dev

Angular 4: using component variables inside custom validator functions

From Dev

Access a service from a custom validator in Angular2

From Dev

Calling $.ajax inside form validator

From Dev

Inject custom service into a custom Validator

From Dev

Django form not calling custom validator

From Dev

Angular 5 FormGroup validator web service result not triggering ngIF hasError

From Dev

Custom validator in Laravel 5

From Dev

Angular 5: calling method from html

From

How to implement Custom Async Validator in Angular2/4/5

From Dev

How to write a custom validator the uses external data Angular 5

From Dev

How to use custom Validator in Angular5 and spring-boot

From Dev

Custom compare password validator and this [Angular 2,4,5,6]

From Dev

Angular(2/4/5/6) Custom validator error message not showing

From Dev

Custom Validator Angular 2

From Dev

Angular custom Validator checkbox

From Dev

Calling a method inside a method

Related Related

  1. 1

    NestJs - Calling a method from a service inside a Custom Decorator

  2. 2

    Calling a method of same service is not working inside jsPDF, Angular

  3. 3

    Using Observable inside Custom Validator Angular

  4. 4

    Angular 5: Using Service from inside Custom Decorator Function

  5. 5

    Inject a service in a custom validator in Angular2

  6. 6

    Access service from Custom Validator in Angular

  7. 7

    method inside service is not function in angular 5 unit tests with karma

  8. 8

    Angular5 Custom Validator for Date Min

  9. 9

    GoogleApiClient not calling onConnected method inside service

  10. 10

    Angular service always undefined when calling in async validator

  11. 11

    Creating and calling a custom function inside an angular class

  12. 12

    Angular 1.5: calling a method of a component inside ngRepeat

  13. 13

    Calling a method inside *ngIf mutliple times angular

  14. 14

    Angular 4: using component variables inside custom validator functions

  15. 15

    Access a service from a custom validator in Angular2

  16. 16

    Calling $.ajax inside form validator

  17. 17

    Inject custom service into a custom Validator

  18. 18

    Django form not calling custom validator

  19. 19

    Angular 5 FormGroup validator web service result not triggering ngIF hasError

  20. 20

    Custom validator in Laravel 5

  21. 21

    Angular 5: calling method from html

  22. 22

    How to implement Custom Async Validator in Angular2/4/5

  23. 23

    How to write a custom validator the uses external data Angular 5

  24. 24

    How to use custom Validator in Angular5 and spring-boot

  25. 25

    Custom compare password validator and this [Angular 2,4,5,6]

  26. 26

    Angular(2/4/5/6) Custom validator error message not showing

  27. 27

    Custom Validator Angular 2

  28. 28

    Angular custom Validator checkbox

  29. 29

    Calling a method inside a method

HotTag

Archive