使用外部服务验证表单

问题描述 投票:2回答:1

我正在尝试使用外部服务验证Angular表单,但我收到cannot read property of undefined错误。

我在我的组件中创建了一个简单的表单:

this.myForm = this.fb.group({
  username: ['', [this.validator.username]],
});

从那里,我正在调用我的username方法:

@Injectable()
export class ValidatorService {
  constructor(private auth: AuthService) {}
  username(input: FormControl): {[key: string]: any} {
    return { userInvalid: this.auth.validate(input.value) };
  }
}

然后,我的ValidatorService调用一个方法来检查服务器是否存在该用户名:

@Injectable()
export class AuthService {
  validate(username: string): boolean {
    return username !== 'demo';
  }
}

我收到以下错误:Cannot read property 'auth' of undefined。请问有什么想法吗?

Live demo

javascript angular typescript
1个回答
1
投票

username方法执行就像一个函数不像ValidationService的方法所以你正在失去上下文this

Function.prototype.bind方法应该帮助你:

username: ['', [this.validator.username.bind(this.validator)]],
© www.soinside.com 2019 - 2024. All rights reserved.