代码之家  ›  专栏  ›  技术社区  ›  user979331

角度2“无法读取未定义的属性”dataService“`

  •  0
  • user979331  · 技术社区  · 6 年前

    我正在使用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};
            }
    

        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};
                }
    
        }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Andreq Frenkel    6 年前

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