我正在使用DevExtreme组件,这是在html中调用回调函数的地方:
<dxi-validation-rule type="custom"
[validationCallback]="validationCallback"
message="Email exists">
</dxi-validation-rule>
在ts文件中:
validationCallback (e) {
const x = this.userService.getUserByEmail(e.value);
x.subscribe(ref => ref.email != null ? true : false);
return x;
}
服务代码:
getUserByEmail(email: string): Observable<User> {
return this.afs
.collection<User>('users', ref => ref.where('email', '==', email))
.snapshotChanges()
.map(
users => {
const user = users[0];
if (user) {
const data = user.payload.doc.data() as User;
const id = user.payload.doc.id;
console.log('found: ' + data.email);
return { id, ...data };
} else {
return null;
}
}
);
}
该代码的问题是我得到了
Cannot read property 'getUserByEmail' of undefined
基本上意味着我正在尝试访问this.userService
,这超出了函数的范围。在这种情况下,我如何能够访问外部功能来验证电子邮件?
答案 0 :(得分:0)
可能是一种方法,方法是创建一个返回箭头函数的方法,然后以这种方式将getUserByEmail
设置为该箭头函数,您将获得对该对象的引用
public getUserByEmail;
ngOnInit() {
this.getUserByEmail = getUserByEmailFactory();
}
getUserByEmailFactory() {
return (email: string) => {
return this.afs
.collection<User>('users', ref => ref.where('email', '==', email))
.snapshotChanges()
.map(
users => {
const user = users[0];
if (user) {
const data = user.payload.doc.data() as User;
const id = user.payload.doc.id;
console.log('found: ' + data.email);
return { id, ...data };
} else {
return null;
}
}
);
}
}
您可以从
afs
到getUserByEmailFactory
,然后return函数将有一个闭包,然后您将不再需要使用this
public getUserByEmailFactory(afs){
...
}
ngOnInit() {
this.getUserByEmail = getUserByEmailFactory(this.afs);
}
或者可以像这样
public getUserByEmail = () => { ... }