0

I have a component that is present on my application in two differente place. This component has a dependency, one service, that fetch your data by http call.

I don't want that this service does two http call, but only one.

This is my component:

export class MenuFrontComponent {
  menu: any;
  constructor(private router: Router, public l: LanguageService, private _menu: MenuService) {
    this._menu.getMenu().subscribe((menu) => {
      this.menu = menu;
    });
  }

This is my service:

constructor(private client: ClientService, public l: LanguageService) {
    this.client.getMenu(this.l.getLang).subscribe(data => {
      this.menu = data;
    });    
  }

  getMenu(): any {
    return new Observable(observer => {
        let int = setInterval(()=>{
          if(this.menu){
            observer.next(this.menu);
            observer.complete();
            clearInterval(int);
          }
        }, 200);
    });
  }

I'm using a setInterval to avoid that this call is done two times, because my component, present two times, calls at the same time, getMenu by MenuService.

I hope to explain well.

feofff
  • 1
  • Does this answer your question? [Angular 2 cache observable http result data](https://stackoverflow.com/questions/41554156/angular-2-cache-observable-http-result-data) – jonrsharpe Mar 18 '20 at 22:28

2 Answers2

0

Try using the first() rxjs operator

0

One way is to cache the data as shown in comments. Other quicker way would be move the HTTP call into the parent component and send the response as an input property to the child component.

Service

constructor(private client: ClientService, public l: LanguageService) { }

getMenu(): any {
  return this.client.getMenu(this.l.getLang);
}

Parent component

export class AppComponent {
  menu: any;

  constructor(private _menu: MenuService) {
    this._menu.getMenu().subscribe((menu) => {
      this.menu = menu;
    });
  }
}

Child component

import { Component, Input } from '@angular/core';

export class MenuFrontComponent {
  @Input() menu: any;

  constructor(private router: Router, public l: LanguageService, private _menu: MenuService) { }
}

Parent component template

<app-front-component [menu]="menu"><app-front-component>
<app-front-component [menu]="menu"><app-front-component>
ruth
  • 29,535
  • 4
  • 30
  • 57