简体   繁体   English

使用一个REST调用的Angular2多个组件

[英]Angular2 multiple components using one REST call

I am part of a Angular2 application (we use beta3) and the issue is the following: 我是Angular2应用程序的一部分(我们使用beta3),问题如下:

Usually we have a component that uses some service that uses some rest call and the component displays the data. 通常我们有一个组件使用一些使用一些休息调用的服务,组件显示数据。 Great. 大。

However we do have a page with more then 6 components all of them using the same REST call...(the backend returns data for ALL of them) and it doesn't make sense to call 6 times the REST for each component, also it will be weird if we do some client side caching. 但是我们确实有一个包含6个以上组件的页面,所有这些组件都使用相同的REST调用...(后端返回所有这些组件的数据),并且为每个组件调用6次REST是没有意义的,如果我们做一些客户端缓存会很奇怪。

Is there something available out of the box ? 是否有开箱即用的东西? Or a Pattern to handle such case? 还是一个处理这种情况的模式?

Thanks. 谢谢。

Just do it in a shared service. 只需在共享服务中执行此操作即可。 If you add it only in bootstrap(..., [OtherProviders, HTTP_PROVIDERS, MyService]) each component will get injected the same instance. 如果只在bootstrap(..., [OtherProviders, HTTP_PROVIDERS, MyService])添加它bootstrap(..., [OtherProviders, HTTP_PROVIDERS, MyService])每个组件将被注入相同的实例。 Store the data in the service and every component can access it 将数据存储在服务中,每个组件都可以访问它

export class MyComponent {
  constructor(private dataService:MyService) {
    dataService.getData().subscribe(data => { this.data = data; });
  }
}
export class MyService {
  getData() {
    if(!this.data) {
      return http.get(...).map(...).subscribe(data => { this.data = data;});
    } 
    return this.data;
  }
}

The @Günter's answer really makes sense! @Günter的答案真的很有意义!

I don't know your code is organized but observable can also be subscribed several times. 我不知道你的代码是有组织的,但也可以多次订阅可观察的代码。 To do that you need to make them "hot" using the share operator: 要做到这一点,你需要使用share运算符使它们“热”:

export class MyService {
  dataObservable:Observable;

  initDataObservable() {
    this.dataObservable = http.get(...).map(...).share();
  } 
}

Without using the share operator, corresponding request will executed several times (one per subscribe). 不使用share运算符,相应的请求将执行几次(每个订阅一个)。

You can notice that the request will be executed once one subscribe method is called on the observable. 您可以注意到,一旦在observable上调用了一个subscribe方法,就会执行该请求。

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

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