简而言之:我通过调用一个调用第二个数据服务的服务来初始化Angular应用程序。在中间服务从数据服务接收并处理其数据之后,它必须通过Observable或Subject与应用程序通信,该应用程序可以继续加载。我想短路任何后续调用相同的方法。
export class MiddleService {
private triedOnce = false;
private isLoadedSubject = new AsyncSubject();
public loadConfig (): AsyncSubject<any> {
if (!this.triedOnce) {
this.isLoadedSubject.next(false);
this.dataService.getConfiguration(...).subscribe(
(data) => {
// do stuff with data
this.isLoadedSubject.next(true);
}
);
this.isLoadedSubject.complete();
this.triedOnce = true;
}
return this.isLoadedSubject;
}
}
我想,第一个问题是,如果使用这样的主题是反模式或非标准使用。 (Does this apply?)
其次,我觉得我应该重用并能够重用isLoadedSubject
而不需要单独的布尔值。我不知道如何在订阅和complete
回调之外做到这一点。 AsyncSubject
有一个isCompleted
财产,但它是私人的。
我会做的事情如下:
export class MiddleService {
public readonly config$ = this.dataService.getConfiguration(...)
.pipe(shareReplay(1));
}
这将延迟获取配置,并将为所有后续调用缓存它。