【发布时间】:2021-08-11 20:22:54
【问题描述】:
在我的 Angular Web 应用程序中,我必须获取特定数据,但在我必须检查用户是否登录之前,我需要加载一些额外的数据。假设我想获取登录用户的订单,但要获取订单,我必须等待,直到加载用户所属的组,因为我需要它来加载订单。 (非常简化我的情况)
所以我创建了一个暂停类,以便我可以在我的项目中重用它:
import { BehaviorSubject } from "rxjs";
export class Pauser {
private pauses: string[];
pauser$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(pauses: string[]) {
this.pauses = pauses;
}
getPauser$() {
return this.pauser$;
}
getLength() {
return this.pauses.length;
}
removePause(pause: string) {
const index = this.pauses.findIndex(p => { return p === pause });
if (index != undefined){
this.pauses.splice(index,1);
this.pauser$.next(this.getLength() == 0);
}
}
}
现在我的订单组件如下所示:
private initPauser: Pauser = new Pauser(["group"]);
constructor(private authService: AuthService,
private groupDataService: GroupDataService) {
super();
this.authService.getAuthenticated$().pipe(
// Check if user is logged in
switchMap(auth => {
if (auth != null) {
return this.initPauser.getPauser$();
}
else {
return of(null);
}
}),
takeUntil(this.destroyed$)
).pipe(
takeUntil(this.destroyed$)
).subscribe(pauser => {
if (pauser != null) {
// Check if data already loaded
if (pauser) {
// Load the order Data
this.onChange();
} else {
// Data not loaded -> Wait until the data is loaded
// THIS FUNCTION RETURNS UNDEFINED ALTHOUGH IN DEBUGGER IT IS DEFINED
this.initPauser.getPauser$().pipe(takeUntil(this.destroyed$))
.subscribe(res => {
if (res) {
// Load the order Data
this.onChange();
}
})
}
}
});
this.groupDataService.getActiveGroup$().pipe(takeUntil(this.destroyed$))
.subscribe(group => {
if (group != null) {
this.activeGroup = group;
if (this.initPauser.getLength() > 0) this.initPauser.removePause("group");
}
})
}
如上所述,在检查后,如果数据已经加载(并且没有),我试图将 pauser$ 行为主题返回为可观察的,以便我可以订阅它。但函数返回未定义。
更奇怪的是,当我在调试时将鼠标悬停在getPauser()$ 的第一个函数调用上时,调试器说它将返回未定义,但它正常运行并将行为主题返回为可观察的。与第二个函数调用相同,但这次它确实返回 undefined。
【问题讨论】:
-
如果您解决了您的问题,最好在下面添加解决方案的答案(而不是将其编辑到问题中)并接受您自己的答案。
标签: angular typescript rxjs