Rxjs方法让调用者知道方法完成,并缓存该结果

问题描述 投票:0回答:1

简而言之:我通过调用一个调用第二个数据服务的服务来初始化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财产,但它是私人的。

angular rxjs rxjs6
1个回答
1
投票

我会做的事情如下:

export class MiddleService {
   public readonly config$ = this.dataService.getConfiguration(...)
        .pipe(shareReplay(1));
}

这将延迟获取配置,并将为所有后续调用缓存它。

另见:Angular 5 caching http service api calls

© www.soinside.com 2019 - 2024. All rights reserved.