Home > database >  Angular service is called twice when have multiple components
Angular service is called twice when have multiple components

Time:09-29

I have an angular page with includes the same component twice. A small presentation and a popup.

Both components should use the same dataset as retrieved from the server. But how to avoid that the service is called twice? The server can handle this, but it is a waste of bandwidth. Not nice for mobile users.

Of course, I can load the data on the parent component, but I think this is not the way forward. The parent component should not have any knowledge of the child data.

CodePudding user response:

As rightly suggested by @jonrsharpe in the comments section of the question, you can store the response in the injectable service and return the response as an observable in subsequent calls. In order to implement this, you can modify the injectable service in the following way,

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable, of } from 'rxjs';

export class HttpService {

  constructor(private http: HttpClient) { }
  
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json'
    })
  };

  responseBody: any;


  postResponse(requestObject: any ) {
    return this.http.post(API_URL, requestObject, this.httpOptions); // Method gets invoked initially
  }

  storeResponse(response: any) {
    this.responseBody = response; // Method gets invoked after the initial call has received the response object
  }

  getResponse():Observable<any[]> {
    return of(this.responseBody); // Method gets invoked by subsequent calls
  }

}

CodePudding user response:

See if this pseudocode works for you:

export class HttpService {

  constructor(private http: HttpClient) { }
  
  public data$ = this.http.get("api").pipe(
    shareReplay({bufferSize: 1, refCount: boolean})
  )
}

bufferSize obviously sets the buffer size to 1, so only the latest value is replayed, and refCount will cause the request to be executed again after all the subscribers have unsubscribed and something is subscribing again (if you want it to be cached indefinitely, just use shareReplay(1))

  • Related