在 RxJs 5 中共享 Angular Http 网络调用结果的正确方法是什么? [英] What is the correct way to share the result of an Angular Http network call in RxJs 5?

查看:21
本文介绍了在 RxJs 5 中共享 Angular Http 网络调用结果的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用 Http,我们调用了一个方法,该方法进行网络调用并返回一个 http observable:

By using Http, we call a method that does a network call and returns an http observable:

getCustomer() {
    return this.http.get('/someUrl').map(res => res.json());
}

如果我们使用这个 observable 并向其添加多个订阅者:

If we take this observable and add multiple subscribers to it:

let network$ = getCustomer();

let subscriber1 = network$.subscribe(...);
let subscriber2 = network$.subscribe(...);

我们要做的是确保这不会导致多个网络请求.

What we want to do, is ensure that this does not cause multiple network requests.

这似乎是一个不寻常的场景,但实际上很常见:例如,如果调用者订阅了 observable 以显示错误消息,并使用异步管道将其传递给模板,我们已经有两个订阅者.

This might seem like an unusual scenario, but its actually quite common: for example if the caller subscribes to the observable to display an error message, and passes it to the template using the async pipe, we already have two subscribers.

在 RxJs 5 中这样做的正确方法是什么?

What is the correct way of doing that in RxJs 5?

也就是说,这似乎工作正常:

Namely, this seems to work fine:

getCustomer() {
    return this.http.get('/someUrl').map(res => res.json()).share();
}

但这是在 RxJs 5 中这样做的惯用方式,还是我们应该做其他事情?

But is this the idiomatic way of doing this in RxJs 5, or should we do something else instead?

注意:根据 Angular 5 新的 HttpClient,所有示例中的 .map(res => res.json()) 部分现在是无用的,因为现在默认采用 JSON 结果.

Note : As per Angular 5 new HttpClient, the .map(res => res.json()) part in all examples is now useless, as JSON result is now assumed by default.

推荐答案

截至 2021 年,正确的方法是使用 RxJs 原生提出的 shareReplay 运算符.在下面的答案中查看更多详细信息.

as of 2021, the proper way is to use the shareReplay operator natively proposed by RxJs. See more details in below answers.

缓存数据,如果可用缓存,则返回此数据,否则发出 HTTP 请求.

Cache the data and if available cached, return this otherwise make the HTTP request.

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of'; //proper way to import the 'of' operator
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/map';
import {Data} from './data';

@Injectable()
export class DataService {
  private url: string = 'https://cors-test.appspot.com/test';
  
  private data: Data;
  private observable: Observable<any>;

  constructor(private http: Http) {}

  getData() {
    if(this.data) {
      // if `data` is available just return it as `Observable`
      return Observable.of(this.data); 
    } else if(this.observable) {
      // if `this.observable` is set then the request is in progress
      // return the `Observable` for the ongoing request
      return this.observable;
    } else {
      // example header (not necessary)
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      // create the request, store the `Observable` for subsequent subscribers
      this.observable = this.http.get(this.url, {
        headers: headers
      })
      .map(response =>  {
        // when the cached data is available we don't need the `Observable` reference anymore
        this.observable = null;

        if(response.status == 400) {
          return "FAILURE";
        } else if(response.status == 200) {
          this.data = new Data(response.json());
          return this.data;
        }
        // make it shared so more than one subscriber can get the result
      })
      .share();
      return this.observable;
    }
  }
}

Plunker 示例

本文 https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html 很好地解释了如何使用 shareReplay 进行缓存.

This article https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html is a great explanation how to cache with shareReplay.

这篇关于在 RxJs 5 中共享 Angular Http 网络调用结果的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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