【问题标题】:Duplicated Http requests with Observable.ForkJoin in Angular 5在 Angular 5 中使用 Observable.ForkJoin 重复 Http 请求
【发布时间】:2018-06-13 20:07:30
【问题描述】:

我有一个 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 调用中的每一个都运行了两次。我做错了什么?

【问题讨论】:

  • 可能是预检请求。如果你在第一个请求中看到这个Request Method:OPTIONS,那就没问题了。
  • 谢谢,我已经检查过了。 :-) 这不是预检

标签: javascript angular observable


【解决方案1】:

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>

【讨论】:

  • 太好了,谢谢你解释发生了什么
  • 我使用 .share() 进行了此操作,但我正在查看您建议的第二个选项 - 语法导致我出现很多错误,这行是否正确:[highlightedInsight、insights、topics]?
猜你喜欢
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多