可观察的订阅内容未执行

时间:2019-01-28 02:55:30

标签: angular typescript rxjs

HTML组件中的提交按钮将触发名为addCollaborators()的函数。相关代码如下:

component.ts

emails: string[] = [];

constructor(public userService: UserService) {}

// This is the function called from the HTML
addCollaborators() {
  this.emails.forEach(email => {
    const user = this.getUserFromEmail(email);
    if (user instanceof User) {
      this.counterService.someDbFunction();
    }
  });

  this.dialogRef.close();
}

getUserFromEmail(emailAddress: string): User | void {
  console.log("Code is reached here");
  this.userService.users$.subscribe((users: User[]) => {
    console.log("This is never reached");
    for (const user of users) {
      if ( /* Some boolean logic */ ) {
        return user;
      }
    }
  });
}

user.service.ts

users$: Observable<User[]>;

如log语句中所述,getUserFromEmail内订阅中的任何代码均未执行。这很明显,因为没有执行任何操作,并且控制台中没有该消息。 users$观察值已填充到服务构造函数中,并已在其他位置成功订阅。实际上,component.ts的构造函数中的以下语句是成功的:

this.userService.users$.subscribe(users => console.log(users));

请让我知道其他信息是否对您有所帮助,并提前致谢。

更新

以下内容不会记录任何内容,因此它可能是比以前认为的更根本的问题。

addCollaborators() {
  console.log("I am logged");
  this.userService.users$.subscribe(users => console.log("I am not", users));
}

相关的HTML:

<button mat-fab
        (click)="addCollaborators()"
        class="add-collaborators">
<mat-icon>group_add</mat-icon>
</button>

1 个答案:

答案 0 :(得分:1)

在此处检查working Stackblitz;您能否尝试用您的代码扩展该示例,以便我们查看是否遇到任何错误...

请在您的订阅中添加错误最后阻止(如下所示),以查看是否存在任何错误...

  getUserFromEmail(emailAddress: string): User | void {
    console.log("Code is reached here for "+ emailAddress);
    this.userService.users$().subscribe(

  /* DATA BLOCK */    
  (users: User[]) => 
  {
  console.log("This is never reached");
    for (const user of users) {
      /* if ( //Some boolean logic ) { return user; } */
    }
  } 
  /* ERROR BLOCK */    
  , errr => { console.log(errr); }
  /* FINALLY BLOCK */    
  , () => { console.log("this is the finally block");}
);

}

相关问题