Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my Chrome network tab, each of the 3 API calls is running twice. What am I doing wrong?

like image 716
Evonet Avatar asked Jan 04 '18 05:01

Evonet


1 Answers

Both the async pipe and the forkJoin.subscribe are creating separate network requests.

Use Observable.share to prevent resubscribing

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:

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>
like image 130
hayden Avatar answered Sep 25 '22 17:09

hayden