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

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

问题描述

我创建了一个演示(

问题:

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

解决方案在这里

解决方案

如果每次都调用this.http.get(API_ENDPOINT).pipe(shareReplay(1)),每次http请求会被触发.如果你想进行一次http调用并缓存数据,建议使用以下方法.

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

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

现在订阅多次:

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

您的服务:

public getData() {返回 this.http.get(API_ENDPOINT)}

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))
  }

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

Question:

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 ?

Edit: solution is here

解决方案

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

Now subscribe multiple times:

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

Your service:

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

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

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