简体   繁体   English

如何在.subscribe中调用方法?

[英]How to call method inside .subscribe?

I'm trying out Angular8 and Google Firestore. 我正在尝试Angular8和Google Firestore。 I'd like to add some additional information regarding a "member" when a member is a authenticated user. 当成员是经过身份验证的用户时,我想添加一些有关“成员”的附加信息。 But, I only like to do this if the member-document doesn't exist. 但是,我只喜欢在成员文档不存在的情况下执行此操作。 For this I'm using the attached code. 为此,我使用了随附的代码。 The problem is that the addMember-method can't be called from where I would like it to be called (see attached code). 问题在于无法从我希望调用的地方调用addMember方法(请参阅随附的代码)。 This gives this error: "ERROR TypeError: this.addMember is not a function". 这给出了此错误:“ ERROR TypeError:this.addMember不是函数”。

addMember can be called with out problem if it's placed "outside" of ".subscribe(function (doc) {". 如果将addMember放在“ .subscribe(function(doc){”)的“外部”,则可以毫无问题地进行调用。

Why is this? 为什么是这样? Any suggestions on solving this would be appriciated. 解决该问题的任何建议都将适用。


createMember() {
    alert(this.member.email);
    var docRef = this.db.collection("member").doc(this.member.orgId + '_' + this.member.email);


    docRef.get().subscribe(function (doc) {
      if (doc.exists) {
        console.log("Document data: ", doc.data());
      } else {
        this.addMember();
        //console.log('No such document! -> Add Member');
        // doc.data() will be undefined in this case

      }

    });

}

addMember(){
      this.userService.addMember(this.member)
        .then(res => {
          alert('Success!');
        });
  }

You can use a paramater, for example self 您可以使用参数,例如self

let self = this;
docRef.get().subscribe(function (doc) {
      if (doc.exists) {
        console.log("Document data: ", doc.data());
      } else {
        self.addMember();
        //console.log('No such document! -> Add Member');
        // doc.data() will be undefined in this case

      }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM