【发布时间】:2021-07-16 12:12:22
【问题描述】:
我在使用 .subscribe() 时遇到问题,我用来更新 UI 的值本身并没有更新。在我的 Inspect Element Network 标签中,我可以看到数据是正确的。在任何人提到它之前,嵌套的.subscribe() 不是问题,第一次订阅总是正确的,因为用户必须登录才能查看此屏幕。
ngOnInit(): void {
this.service.isLoggedIn().subscribe( u => {
this.user = u;
this.id = this.location.selected.value.id
this.location.getSelected().subscribe( selectedLocation => {
if (selectedLocation) {
this.showTable = true;
if (selectedLocation.members) {
this.member = true;
}
if (selectedLocation.schedules) {
this.schedules = true;
}
if (selectedLocation.team) {
this.team = true;
}
}
});
});
getSelected(): Observable<Location> {
if (this.selected && this.selected.value) {
return of(this.selected.value);
} else {
return this.selected.asObservable();
}
}
这是检查元素中我的网络选项卡中显示的内容:
{
"id": 4,
"member": true,
"schedules": true,
"team": false
}
但是,例如,当我转到此页面时,if(selectedLocation) 被触发,但其他if()s 没有,因此我的变量没有改变,因此 UI 也没有。
【问题讨论】:
-
如果请求是异步的,您可能需要自己触发变更检测。
-
1. 嵌套订阅可以替换为
forkJoin2. 这与错误有关:你如何获得当您显示的函数getSelected()清楚地返回BehaviorSubject或者它是.value而不是HTTP 请求时,浏览器控制台网络中的响应? -
@martin 嗨,谢谢您的回复,我之前看到有人提到过更改检测,
markForCheck()和detectChanges()但几乎没有解释如何使用它们,或者它们是如何工作的. -
@MichaelD 我不完全确定你的第二点,我刚离开大学并开始在一家新公司工作,我没有建立这个项目,我只是被要求修复这个错误.
标签: angular rxjs observable subscribe behaviorsubject