Duplicated Http requests with Observable.ForkJoin

2019-04-28 02:45发布

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?

1条回答
我命由我不由天
2楼-- · 2019-04-28 03:32

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>
查看更多
登录 后发表回答