Angular 5:在自定义验证器中调用服务方法

时间:2018-11-12 13:50:44

标签: angular

基本上,我已经创建了具有getUserByAlias方法的用户服务。出于测试目的,它除了打印出字符串外什么也不做。我一直在关注视频教程,并且在教程中,他基本上表明您需要确保服务已导入,然后包含在@component中,然后包含在构造函数中。 所以我的文件看起来像这样:

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

当输入触发checkUsername时,我得到了错误:ERROR TypeError: Cannot read property 'userService' of undefined。我在构造函数内部调用了this.userService.getUserByAlias('test'),并打印出来以控制台所需的内容。因此,我认为这是行不通的,因为在自定义验证器中有一些事情要做。为什么在验证器中不起作用?怎样使它起作用?

1 个答案:

答案 0 :(得分:3)

原因是因为std::array的上下文丢失了。

要解决此问题,可以使用this函数,如下所示:

bind

这会将正确的上下文绑定到该函数以确保其正常工作