在Angular中使用shareReplay(1)-仍会调用http请求吗? [英] Using shareReplay(1) in Angular - still invokes http request?

查看:113
本文介绍了在Angular中使用shareReplay(1)-仍会调用http请求吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个演示( ng-run )我有一个用于调用Http请求的按钮.

I've created a demo (ng-run) where I have a button which invokes an Http request.

单击按钮时,我将调用此方法:

When the button is clicked, I invoke this method :

public getData(){
 this._jokeService.getData().subscribe();
}

从服务中依次调用此内容:

Which in turn invokes this ( from a service) :

 public getData() {
    return this.http.get(API_ENDPOINT).pipe(shareReplay(1))
  }

问题在于每次点击-我仍然看到启动了一个新的http请求:

The problem is that on every click - I still see a new http request initiated :

问题:

为什么不使用shareReplay保留响应的最后一个值?
如何使我的代码仅调用一次http并将该值保留给以后的订阅?

Why doesn't shareReplay keeps the last value of the response?
How can I make my code to invoke the http only once and keep that value for future subscriptions ?

解决方案在这里

推荐答案

如果每次调用this.http.get(API_ENDPOINT).pipe(shareReplay(1)),每次都会触发http请求.如果要进行一次HTTP调用并缓存数据,建议执行以下操作.

If you call every time this.http.get(API_ENDPOINT).pipe(shareReplay(1)), each time http request will be triggered. If you want to make http call once and cache data, the following is recommended.

您首先获得可观察的数据:

You first get the observable for data:

 ngOninit(){
    this.data$ =  this._jokeService.getData().pipe(shareReplay(1));
    }

现在订阅多次:

 public getData(){
     this.data$.subscribe();
    }

您的服务:

public getData() {
    return this.http.get(API_ENDPOINT)
  }

这篇关于在Angular中使用shareReplay(1)-仍会调用http请求吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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