gpt4 book ai didi

validation - 在 Angular2 的自定义验证器中注入(inject)服务

转载 作者:太空狗 更新时间:2023-10-29 17:09:47 25 4
gpt4 key购买 nike

我尝试在自定义验证器中使用服务来检查用户名是否已存在。

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' 引用控件而不是我的类。服务未定义。我如何在验证器中使用我的服务?

更广泛地说,我如何在自定义验证器中传递参数?

最佳答案

您需要在验证中控制this 的含义。您可以使用 bind 来做到这一点

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

然后其他一切都应该按预期工作。

关于validation - 在 Angular2 的自定义验证器中注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com