【问题标题】:Angular 2 `Cannot read property 'dataService' of undefined`Angular 2`无法读取未定义的属性'dataService'
【发布时间】:2019-02-12 09:01:41
【问题描述】:

我正在使用 Angular 2,我试图在一个方法中调用它,但我收到一个错误:Cannot read property 'dataService' of undefined

passwordMatchValidator(g: FormGroup) {
                        console.log(this.dataService);
                        return g.get('password').value === g.get('repeat').value ? null : {'mismatch': true};
        }

当我可以在它工作的方法之外使用 this.dataService 时,这是因为它现在是 FormGroup 吗?如果是这样,我将如何在此方法中调用 this.dataService?

    import { DataService } from '../../services/data.service';

    @Component({
            selector: 'app-register',
            templateUrl: './register.component.html',
            styles: []
    })
    export class RegisterComponent{

    constructor(private fb: FormBuilder,
                    private locationService: LocationService,
                    private dataService: DataService){}

buildForm(): void {    

this.step1Form = this.fb.group({
                username: new FormControl('', {
                        validators: [Validators.required,
                        Validators.minLength(4)],
                }),
                email: new FormControl('', {
                        validators: [Validators.required,
                        Validators.pattern("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")],
                }),
                password: new FormControl('', {
                        validators: [Validators.required,
                        Validators.minLength(8)],
                }),
                repeat: new FormControl('', {
                        validators: [Validators.required,
                        Validators.minLength(8)],
                }),
                }, { validator: this.passwordMatchValidator });

}

    passwordMatchValidator(g: FormGroup) {
                            console.log(this.dataService);
                            return g.get('password').value === g.get('repeat').value ? null : {'mismatch': true};
            }

    }

【问题讨论】:

  • 显示完整代码
  • 你如何分配这样的验证器?

标签: angular angular2-forms angular2-services


【解决方案1】:

当你将验证器分配给控制时,你必须保存上下文,例如:

fb.group({
  password: [null, this.passwordMatchValidator.bind(this)]
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2017-07-08
    • 2017-03-31
    • 2017-06-26
    • 1970-01-01
    相关资源
    最近更新 更多