我试图向用户显示他们可以添加的“报告”列表,这些报告需要多个AJAX请求和observable的组合 - 一个请求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请求。
答案取决于应用程序的整体架构。如果您遵循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()
)
}
使用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'))
)
)))
);
}
谢谢大家的建议。我更了解发生了什么,并且肯定清理了很多代码。当任何应用程序报告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请求。