-1

How can I make only one http request but subscribe multiple times to the service?

The documentation states that they are called multiple times:

const req = http.get<Heroes>('/api/heroes');
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.

Source: https://angular.io/guide/http#making-a-delete-request (a bit down).

Is there a way, that the http request is done only once?

Background: I'm making a service which checks if the requests are identically, and if yes, it returns the last observable. Now if the requests are made twice this "optimization" becomes obsolete.

All related answers are to Angular

rjdkolb
  • 10,377
  • 11
  • 69
  • 89
Stefan
  • 14,826
  • 17
  • 80
  • 143
  • Subscribe once on your request and store the output in some variable of type Observable and subscribe to that variable instead of http request again. – eduPeeth Jul 25 '18 at 07:53
  • @eduPeeth how to best create such a observable? https://angular.io/guide/observables looks pretty complex – Stefan Jul 25 '18 at 08:03
  • what's the type of Heroes here? looks like array of hero? – eduPeeth Jul 25 '18 at 08:11
  • Does that help ? https://stackoverflow.com/questions/39627396/angular-2-observable-with-multiple-subscribers – David Jul 25 '18 at 08:11

1 Answers1

0

Based on comments I solved it like this:

this.lastObservable = new Observable(observe => {
        this.http.get(url).subscribe(
          result => {
            // observable execution
            observe.next(result)
          },
          error => {
            observe.error(error)
          },
          () => {
            observe.complete();
          }
        );
Stefan
  • 14,826
  • 17
  • 80
  • 143