我正在尝试向用户显示他们可以添加的“报告”列表,这需要多个AJAX请求和可观察对象的组合-一个对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请求。
答案 0 :(得分:1)
答案取决于应用程序的整体体系结构。如果您遵循Redux样式的架构(ngrx in Angular),则可以通过在商店中缓存API响应(即LoadApplicationsAction => Store => Component(s)
)来解决此问题。
在此流程中,您加载应用程序列表的请求以及每个应用程序的详细信息仅发生一次。
如果您没有实现这样的架构,那么相同的原理仍然适用,但是您的构造/实现会发生变化。按照您的代码示例,您处在正确的轨道上。您可以shareReplay(1)
fetchApplications
的响应,本质上重播源发出给将来的订户的最新值。或者类似地,您可以将结果存储在BehaviorSubject
中,从而获得相似的结果。
无论您是否选择实现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()
)
}
答案 1 :(得分:1)
shareReplay(1)
可以在内部使用ReplaySubject
来实现简单的缓存。
如果您希望将所有ApplicationReports放在一个数组中,而不需要一个接一个地发送它们,则可以使用forkJoin
同时发送多个请求。
最终代码看起来像这样。
private applicationReportsCache$: Observable<ApplicationReports[]>;
constructor(private http: HttpClient) { }
getAllApplicationReports(): Observable<ApplicationReports[]> {
if (!this.applicationReportsCache$) {
this.applicationReportsCache$ = this.requestAllApplicationReports().pipe(
shareReplay(1)
);
}
return this.applicationReportsCache$;
}
private requestAllApplicationReports(): Observable<ApplicationReports[]> {
return this.http.get('api/applications').pipe(
map(http => http['applications'] as Application[]),
mergeMap(apps =>
forkJoin(apps.map(app =>
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}`);
}
// need to normalize all report urls here
reports.forEach(report => {
report.Url = url.resolve(application.Url, report.Url);
});
const applicationReports = new ApplicationReports();
applicationReports.Application = app;
applicationReports.Reports = reports;
return applicationReports;
}),
catchError(err => of('ERROR'))
)
)))
);
}
答案 2 :(得分:0)
感谢大家的建议。我更好地了解正在发生的事情,并且肯定清理了很多代码。当任何应用程序报告ajax请求出错时,很难理解如何继续流,但是,catchError()和filter()的组合解决了这个问题。
private _reports: Observable<Report[]>;
public getReports() {
if (!this._reports) {
this._reports = this.fetchApplications().pipe(
mergeMap((applications) => from(applications).pipe(
mergeMap((application) => this.fetchApplicationReports(application).pipe(
catchError(error => {
return of('error');
})
)),
filter(result => {
return result !== 'error';
})
)),
toArray(),
shareReplay(1)
);
}
return this._reports;
}
private fetchApplications(): Observable<Application[]> {
return this._http.get(this._gnetUtilsService.getGnetUrl('api/gnet/applications')).pipe(
map(http => http['applications'] as Application[]
);
}
private fetchApplicationReports(app: Application): Observable<Report[]> {
return this._http.get(url.resolve(app.Url, 'api/reports')).pipe(
map(http => http['data'] as Report[])
);
}
我学到的一些东西
我想我可以多清理一点,但是到目前为止,一切都按我的预期进行-第一个调用getReports()的组件会启动所有ajax请求,所有出错的请求都将被丢弃,并且从不发出,然后所有组件都将获得最终结果,而无需进行更多的ajax请求。