简体   繁体   English

在Angular2中的自定义验证器中注入服务

[英]Inject a service in a custom validator in Angular2

I try to use a service in a custom validator to check if a username already exists. 我尝试在自定义验证器中使用服务来检查用户名是否已存在。

import {Component} from 'angular2/core';
import {
    Control,
    ControlGroup,
    FormBuilder
} from "angular2/common";
import {CharacterService} from "./character-service";

@Component({
    selector: 'register-character-form',
    template: `
        <h2 class="ui header">A new adventurer is coming...</h2>
        <form (ngSubmit)="register()" [ngFormModel]="characterForm" class="ui form">
            <div class="field">
                <label>Nom</label>
                <input ngControl="name">
            </div>
            <button type="submit" class="ui button">Enter in the adventure</button>
        </form>
    `,
    providers: [CharacterService]
})
export class RegisterCharacterFormCmp {
    characterForm: ControlGroup;
    name: Control;

    constructor(private _characterService: CharacterService, fb: FormBuilder) {
        this.name = fb.control('', this.characterNameValidator);

        this.characterForm = fb.group({
            name: this.name
        });
    }

    register(): void {
        //TODO: To implement
    }

    // Not works, this binds the control
    characterNameValidator(control: Control) {
        return this._characterService.isCharacterNameAlreadyExists(control.value) ? {nameCharacterAlreadyExistsError: true} : null;
    }
}

It doesn't work. 它不起作用。 In the characterNameValidator, 'this' references the control and not my class. 在characterNameValidator中,'this'引用控件而不是我的类。 The service is undefined. 该服务未定义。 How can I use my service in the validator ? 如何在验证器中使用我的服务?

More globally, how can I pass arguments in a custom validator ? 更全局,我如何在自定义验证器中传递参数?

You need to control what this means in your validation. 你需要控制什么this意味着您的验证。 You can do so with bind 你可以用bind来做到这一点

this.name = fb.control('', this.characterNameValidator.bind(this));

Everything else should work as expected then. 其他一切应该按预期工作。

您可以使用箭头功能来保持上下文相同。

this.name = fb.control('', (control: Control) => this.characterNameValidator(control));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM