【问题标题】:Observable subscribe content not executing可观察的订阅内容未执行
【发布时间】:2019-06-21 00:59:56
【问题描述】:

组件 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[]>;

如日志语句中所述,getUserFromEmail 内的订阅中的任何代码均未执行。这很明显,因为没有执行任何操作并且控制台中不存在消息。 users$ observable 填充在服务构造函数中,并在其他地方成功订阅。其实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>

【问题讨论】:

  • 如果您要检查用户,您需要在订阅中检查他们。去掉return user if语句,替换成instanceof user if语句。
  • 即使我将所有逻辑都移到了订阅中,操作也无法完成。使用更多信息和测试更新问题。

标签: angular typescript rxjs


【解决方案1】:

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

请在您的订阅中添加 ErrorFinally 块(如下所示),看看是否有任何错误...

  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");}
);

}

【讨论】:

  • 添加错误和 finally 块不会产生额外的日志记录。我将尝试在链接的 Stackblitz 中重现
  • 添加错误块将允许您处理错误...添加 finally 块是个好习惯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
相关资源
最近更新 更多