繁体   English   中英

在Angular 5中使用Observable.ForkJoin进行重复的Http请求

[英]Duplicated Http requests with Observable.ForkJoin in Angular 5

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

}

我的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调用都运行了两次。 我究竟做错了什么?

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

使用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 )不需要,所以可以简化为:

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM