减少多个组件上的同一个http网络调用 [英] Reduce Same http Network call on multiple Component

查看:76
本文介绍了减少多个组件上的同一个http网络调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个组件UsersComponent和HelloComponent.

I have 2 components UsersComponent and HelloComponent.

我在两个组件上使用相同的api调用来调用相同的服务.

I am calling the same service with the same api calls on both the component.

但是我想要的是,如果UsersComponent正在调用api,而不是HelloComponent不应该调用api,那么它应该从UsersComponent接收值.

But I want is that if UsersComponent is calling the api than HelloComponent should not call the api it should recieve the value from UsersComponent.

当前这两个组件上都在进行网络呼叫.

Currently network call is happening on both of the component.

有什么办法.请帮忙.

Stackblitz链接:

Stackblitz link:

Stackblitz

推荐答案

这称为冷观测值.每当您订阅它时,它都会发出一个新的HTTP请求.

This is called as cold observables. Whenever you subscribe to it, it'll make a new HTTP request.

因为每次您返回新的http.get呼叫.

Because every time you return a new http.get call.

这里的解决方案是每次都将相同的指针返回到可观察到的指针.

The solution here is to return the same pointer to that observable every time.

@Injectable()
export class AppService {

  private data$: Observable<any>;

  constructor(private http: HttpClient) {}

  getData() {
     if (!this.data$) {
        this.data$ = this.http.get('https://jsonplaceholder.typicode.com/posts');    
     }
     return this.data$;
  }
}

但是,您可以使用rxjs 运算符.

However, you can use rxjs share operator as well.

这篇关于减少多个组件上的同一个http网络调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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