angular - Angular 6 - 使用范围外的函数和回调函数
问题描述
我正在使用 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
超出函数范围的内容。在这种情况下,我如何能够访问外部函数来验证电子邮件?
解决方案
may be a one way to do it by create a method that return an arrow function then set getUserByEmail
to that arrow function this way you will obtain a reference to this object
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;
}
}
);
}
}
you can an
afs
togetUserByEmailFactory
then the return function will have a closure then you will no longer need to usethis
public getUserByEmailFactory(afs){
...
}
ngOnInit() {
this.getUserByEmail = getUserByEmailFactory(this.afs);
}
or can be like this
public getUserByEmail = () => { ... }
推荐阅读
- matlab - 为什么这个错误信息出现在matlab中(未定义的变量“comm”或类“comm.BCHencoder”)?
- javascript - 使用 Javascript SDK 时,如何在 Amazon Kinesis 消费者中获取最新记录?
- c# - 有没有办法在 Unity 的控制台中使用超链接?
- visual-studio - 如何更改 CMake 生成的 ALL_BUILD 过滤器和 Visual Studio 的 x64 目录的位置?
- php - 如何从 Wordpress 自定义端点内部初始化 POST 和 PUT 方法
- wordpress - 为我的主题制作更新通知功能
- angular - 错误:元数据版本不匹配发现版本 4,预期为 3
- python - Databricks:火花数据框中的 Python 数据透视表
- python - 我应该使用哪种服务在 AWS 上运行计划任务?
- c - 有多少个由N个数字组成的数字,总和为S?(动态规划)