在Angular 5中使用Observable.ForkJoin进行重复的Http请求 [英] Duplicated Http requests with Observable.ForkJoin in Angular 5

查看:178
本文介绍了在Angular 5中使用Observable.ForkJoin进行重复的Http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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;
        });

}

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

在我的Chrome网络标签中,每个3 API调用都运行了两次。我做错了什么?

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

推荐答案

async 管道和 forkJoin.subscribe 正在创建单独的网络请求。

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

使用 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;
    });






但是因为直到结束(当!loading )时,它可以简化为:


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>

这篇关于在Angular 5中使用Observable.ForkJoin进行重复的Http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆