[英]Duplicated Http requests with Observable.ForkJoin in Angular 5
I have an Angular 5 application with the following code in a component: 我有一个Angular 5应用程序,在组件中包含以下代码:
ngOnInit() {
Observable.forkJoin([
this.highlightedInsight = this.insightService.getHighlightedInsight(),
this.insights = this.insightService.getInsightsList(),
this.topics = this.insightService.getInsightTopicsList()
]).subscribe(
response => {},
error => {
console.log('An error occurred:', error);
},
() => {
this.loading = false;
});
}
My html: 我的HTML:
<div class="internal-wrapper" *ngIf="!loading">
<app-highlighted-insight [insight]="highlightedInsight | async"></app-highlighted-insight>
<app-topic-filter [topics]="topics | async"></app-topic-filter>
<app-insight-list [insights]="insights | async"></app-insight-list>
</div>
In my Chrome network tab, each of the 3 API calls is running twice. 在我的Chrome网络标签中,每个3 API调用都运行了两次。 What am I doing wrong? 我究竟做错了什么?
Both the async
pipe and the forkJoin.subscribe
are creating separate network requests. async
管道和forkJoin.subscribe
都在创建单独的网络请求。
Use Observable.share to prevent resubscribing 使用Observable.share防止重新订阅
this.highlightedInsight = this.insightService.getHighlightedInsight().share()
this.insights = this.insightService.getInsightsList().share()
this.topics = this.insightService.getInsightTopicsList().share()
Observable.forkJoin([
this.highlightedInsight, this.insights, this.topics
]).subscribe(
response => {},
error => {
console.log('An error occurred:', error);
},
() => {
this.loading = false;
});
But because the results aren't needed until the end (when !loading
), it can be simplified to this: 但是因为结果在结束时( !loading
)不需要,所以可以简化为:
Observable.forkJoin([
this.insightService.getHighlightedInsight(),
this.insightService.getInsightsList(),
this.insightService.getInsightTopicsList()
]).subscribe(
([highlightedInsight, insights, topics]) => {
this.highlightedInsight = highlightedInsight;
this.insights = insights;
this.topics = topics;
},
error => {
console.log('An error occurred:', error);
}
);
html: HTML:
<div class="internal-wrapper">
<app-highlighted-insight [insight]="highlightedInsight"></app-highlighted-insight>
<app-topic-filter [topics]="topics"></app-topic-filter>
<app-insight-list [insights]="insights"></app-insight-list>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.