简体   繁体   English

在 Angular 中使用 shareReplay(1) - 仍然调用 http 请求?

[英]Using shareReplay(1) in Angular - still invokes http request?

I've created a demo ( ng-run ) where I have a button which invokes an Http request.我创建了一个演示( ng-run ),其中有一个调用 Http 请求的按钮。

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 :问题是在每次点击时 - 我仍然看到一个新的 http 请求被启动:

在此处输入图片说明

Question:题:

Why doesn't shareReplay keeps the last value of the response?为什么 shareReplay 不保留响应的最后一个值?
How can I make my code to invoke the http only once and keep that value for future subscriptions ?如何让我的代码只调用一次 http 并保留该值以供将来订阅?

Edit: solution is here编辑: 解决方案在这里

If you call every time this.http.get(API_ENDPOINT).pipe(shareReplay(1)) , each time http request will be triggered.如果你每次都调用this.http.get(API_ENDPOINT).pipe(shareReplay(1)) ,每次 http 请求都会被触发。 If you want to make http call once and cache data, the following is recommended.如果要进行一次http调用并缓存数据,建议使用以下方法。

You first get the observable for data:您首先获得数据的 observable:

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

In service:在役:

getData$ = this.http.get(API_ENDPOINT).pipe(shareReplay(1));

In component, need to unsubscribe and you can subscribe multiple times with single API call:在组件中,需要取消订阅,您可以通过单个 API 调用多次订阅:

ngOninit(){
   this.data$ =  this._jokeService.getData$;
   this.data$.subscribe() 
}

In template, use:在模板中,使用:

*ngIf="data$ | async as data"

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

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