Duplicate Http requests with Observable.ForkJoin in Angular 5

I have an Angular 5 application with the following code in a component:

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:

 <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> 

On my Chrome network tab, each of the three API calls works twice. What am I doing wrong?

+5
source share
1 answer

Both async and forkJoin.subscribe create separate network requests.

Use Observable.share to prevent re-subscription

 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 since the results are not needed until the end (when !loading ), this can be simplified:

 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:

 <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> 
+4
source

Source: https://habr.com/ru/post/1274491/


All Articles