首页 > 解决方案 > Angular/RxJS - 只调用一次 AJAX 请求,否则发出 Observable 的当前值

问题描述

我正在尝试向用户显示他们可以添加的“报告”列表,这需要多个 AJAX 请求和 observables 的组合——一个对 api 的请求以查找他们可以访问的“应用程序”,然后对定义的多个请求每个应用程序的端点。完成此步骤后,我再也不需要发出 ajax 请求了。

我有一些工作,但我并不真正理解它,我觉得应该有一个更简单的方法来做到这一点。

我现在有一些工作代码,但是,我发现它过于复杂,几乎不明白我是如何让它工作的。

private _applications: ReplaySubject<Application>;
private _applicationReports: ReplaySubject<ApplicationReports>;

// Ajax request to fetch which applications user has access to
public fetchApplications(): Observable<Application[]> {
    return this._http.get('api/applications').pipe(
        map(http => {
            const applications = http['applications'] as Application[];
            applications.forEach(app => this._applications.next(app));
            this._applications.complete();
            return applications;
        })
    );
}

// Returns an observable that contains all the applications
// a user has access to
public getApplications(): Observable<Application> {
    if (!this._applications) {
        this._applications = new ReplaySubject();
        this.fetchApplications().subscribe();
    }
    return this._applications.asObservable();
}

// Returns an observable which shows all the reports a user has
// from all the application they can access
public getApplicationReports(): Observable<ApplicationReports> {
    if (!this._applicationReports) {
        this._applicationReports = new ReplaySubject();
        this.getApplications().pipe(
            mergeMap((app: Application) => {
                return this._http.get(url.resolve(app.Url, 'api/reports')).pipe(
                    map(http => {
                        const reports: Report[] = http['data'];

                        // double check reports is an array to avoid future errors
                        if (!reports || !Array.isArray(reports)) {
                            throw new Error(`${app.Name} did not return proper reports url format: ${http}`);
                        }
                        return [app, reports];
                    }),
                    catchError((err) => new Observable())
                );
            })
        ).subscribe(data => {
            if (data) {
                const application: Application = data[0];
                const reports: Report[] = data[1];

                // need to normalize all report urls here
                reports.forEach(report => {
                    report.Url = url.resolve(application.Url, report.Url);
                });

                const applicationReports = new ApplicationReports();
                applicationReports.Application = application;
                applicationReports.Reports = reports;

                this._applicationReports.next(applicationReports);
            }
        }, (error) => {
            console.log(error);
        }, () => {
            this._applicationReports.complete();
        });
    }
    return this._applicationReports.asObservable();
}

预期功能:

当用户打开“添加报告”组件时,应用程序会启动一系列 ajax 调用以获取用户拥有的所有应用程序以及来自这些应用程序的所有报告。完成所有 ajax 请求后,用户会看到他们可以选择添加的报告列表。如果用户第二次打开“添加报告”组件,他们已经有了报告列表,应用程序不需要发送更多的 ajax 请求。

标签: ajaxangularrxjsobservablerxjs6

解决方案


答案取决于应用程序的整体架构。如果您遵循 Redux 风格的架构(Angular 中的 ngrx),那么您可以通过在存储中缓存 API 响应来解决此问题,即LoadApplicationsAction => Store => Component(s).

在此流程中,您对加载应用程序列表和每个应用程序详细信息的请求仅发生一次。

如果您没有实现这样的架构,那么相同的原则仍然适用,但您的构造/实现会发生变化。根据您的代码示例,您走在正确的轨道上。您可以将shareReplay(1)其响应fetchApplications基本上重播源向未来订阅者发出的最新值。或者类似地,您可以将结果存储在BehaviorSubject实现类似结果的 a 中。

建议

无论您是否选择实现 ngrx,您都可以简化您的 Rx 代码。如果我了解您的预期结果,您只是想向用户显示Report对象列表。如果是这种情况,您可以这样做(未经测试,但应该让您得到正确的结果):

public fetchApplicationReports(): Observable<Report[]> {
  return this._http.get('api/application').pipe(
    mergeMap(apps => from(apps).pipe(
      mergeMap(app => this._http.get(url.resolve(app.Url, 'api/reports'))
    ),
    concatAll()
  )
}

推荐阅读