【问题标题】:Cannot read properties of undefined (reading 'subscribe')无法读取未定义的属性(读取“订阅”)
【发布时间】:2021-11-23 09:55:29
【问题描述】:

我一直在尝试订阅特定的 observable(我是 rxjs 的初学者),但一直失败。 这是我的代码


这里我需要将usergroups数组元素的第一个元素赋给this.currentGroup

const selectedUserGroups$ =
this.userGroupsService.getUserGroupsWithUsers(this.selectedUserGroupIds).pipe(shareReplay());

this.selectedUserGroups$.subscribe( (usergroups: UserGroup[]) =>
this.currentGroup = usergroups[0]); 

if(this.currentGroup.users?.length >0) 
{
  this.showUsersList(); 
}

但这不会像我预期的那样工作,感谢您对此的帮助

【问题讨论】:

  • 你的版本几乎是一个单独的问题,但是:if(this.currentGroup.users?.length >0) 块应该在subscribe 下,在this.currentGroup = 分配之后,否则它会运行得太早。为了进一步阅读,这里有一个常青的 SO 经典:stackoverflow.com/questions/14220321/…

标签: typescript rxjs observable angular10


【解决方案1】:
const selectedUserGroups$ = // assignment here
this.selectedUserGroups$.subscribe( //...

这是两个不同的对象:函数范围内的变量selectedUserGroups$ 和对象属性this.selectedUserGroups$。

例如,从第二行中删除 this.。或将const selectedUserGroups$ = 替换为this.selectedUserGroups$ =。

【讨论】:

  • 感谢这部分解决了我的问题,但不幸的是我还有另一个问题,它不会等到 this.currentGroup 获取值。据我了解,它不是以异步方式工作的。它正在执行下面的行,而无需等待为 this.currentGroup 分配值
  • 仅供参考,我已经编辑了发布的代码,此后我将此 const selectedUserGroups$ 更改为 this.selectedUserGroups$,它已部分解决。正如上面的评论所说,现在它正在执行 if 语句而不等待 this.currentGroup 分配它的值:-(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 2019-10-11
相关资源
最近更新 更多