在Angular2的自定义验证器中注入服务 [英] Inject a service in a custom validator in Angular2

查看:91
本文介绍了在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;
    }
}

它不起作用.在characterNameValidator中,"this"引用控件而不是我的类.服务未定义.如何在验证器中使用我的服务?

It doesn't work. In the characterNameValidator, 'this' references the control and not my class. The service is undefined. How can I use my service in the validator ?

更全面地说,如何在自定义验证器中传递参数?

More globally, how can I pass arguments in a custom validator ?

推荐答案

您需要控制this在验证中的含义.您可以使用 bind

You need to control what this means in your validation. You can do so with bind

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

其他所有操作都应按预期进行.

Everything else should work as expected then.

这篇关于在Angular2的自定义验证器中注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆