【问题标题】:Angular 6 - Using a function outside the scope with a callback function [duplicate]Angular 6 - 使用范围外的函数和回调函数[重复]
【发布时间】:2019-08-11 02:08:30
【问题描述】:

我正在使用 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。在这种情况下,我如何能够访问外部函数来验证电子邮件?

【问题讨论】:

  • 发布您的服务代码
  • 如何将服务注入组件?
  • 使用构造函数,constructor(private userService: UserService){ }
  • 尝试将validationCallback定义为箭头函数:validationCallback = (e) =&gt; { ... }

标签: angular rxjs angular2-services


【解决方案1】:

可能是通过创建一个返回箭头函数的方法然后将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,然后返回函数将有一个闭包,那么您将不再需要使用this

public getUserByEmailFactory(afs){
 ...
}

ngOnInit() {
  this.getUserByEmail = getUserByEmailFactory(this.afs);
}

也可以这样

public getUserByEmail = () => { ... }

arrow function ??

【讨论】:

  • 我应该在 user.service 或 register.component.ts 中添加那个箭头函数吗?
  • register.component.ts 组件内部
  • 这难道不会违背使用 user.service 的目的吗?由于您是从 register.component 内部调用 afs
  • 也可以在服务内部创建一个getUserByEmailFactoryvalidationCallback (e) { const x = this.userService.getUserByEmailFactory()(e.value); x.subscribe(ref =&gt; ref.email != null ? true : false); return x; }
猜你喜欢
  • 1970-01-01
  • 2020-03-11
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多