我想进行一次API调用并将响应存储在服务中,以便从响应中获得的数据可以在多个组件中使用,而无需进行任何额外的API调用。
在所有这些情况下,chartId都是相同的,因此服务器返回相同的响应。在component-1的ngOnInit中,只进行一次getChartDetail调用。在同一组件中,再次进行服务器调用,并且在不是相关组件的组件2中再次进行调用。我如何防止多次服务器调用,而只调用一次,将数据存储在一个单独的函数中,并只调用已经具有所需数据的函数?
以下是我的代码
在图表服务组件中:
getChartDetail(chartId){
const url = 'test/someurl';
return this.service.httpCall('get', url, null)
.map(chart => this.processChart(chart));
}
processChart(chart) {
const result = _.cloneDeep(chart);
_.forEach(result.sections, (section) => {
const subCategories= _.flatMap(section.categories, 'subCategories');
_.assign(section, {
subCategories,
categories:undefined,
});
});
return result;
}在组件1中
ngOnInit() {
this.chartService.getChartDetail(chartId).subscribe((chart) => {
this.data= chart.data;
});
}
notifyAction() {
const chartCountries = this.chartService.getCountries();
const chartRequests = this.chartService
.getChartDetail(chartId)
.concatMap(chart =>
this.chartService.listResults(
this.chart.chartType,
this.chart.chartVersion,
)
));
Observable.zip(chartRequests, chartCountries)
.subscribe(([settings, countries]) =>
this.chartScore = settings;
this.chartEvents = countries;
});
}在组件2中
toggleButton() {
this.chartService.getChartDetail(chartId).subscribe((chart) => {
this.chartprofileDetail(chart);
});
}发布于 2019-04-18 00:20:19
确保将ChartService添加到模块提供程序数组中,以便为整个模块创建一个实例。
在chart.service.ts文件中,创建一个'chart‘字段。
import { of, Observable } from 'rxjs';
@Injectable()
public class ChartService {
private _chart: any // used for caching the value - use your defined type instead
of any
getChartDetail(chartId):Observable<any> {
if(!this._chart) {
const url = 'test/someurl';
return this.service.httpCall('get', url, null)
.map(chart => {
this._chart = chart;
return this.processChart(chart);
}
);
} else {
return of(this.processChart(this._chart));
}
}}
https://stackoverflow.com/questions/55731602
复制相似问题