1

I just noticed that my HTTP calls were not shared anymore between components. I am not sure since which version.

Already checked this solution: Angular2 observable share is not working

which makes the problem even worse (more HTTP calls), I must confess I always had a hard time understanding rxjs.

Here is my service function:

getSomeData(): Promise < any > 
{
    if(this.data) // should keep service from doing extra http for the same request
    {
        return Promise.resolve(this.data);
    }
    else
    {
        return this.http.post(this.createURL('getData',{}),JSON.stringify({}), this.createGetOptions())
            .timeout(environment.timeout)
            .share()
            .map((response: Response) => {
                return response;
            }).toPromise();
    }
}

I call it from different components

this.service.getSomeData().then((data: any) => 
{
    if (data) {
   ...

createGetOptions just adds headers like 'Content-Type': 'text/plain; charset=UTF-8'

Roy
  • 7,811
  • 4
  • 24
  • 47
user7082181
  • 354
  • 3
  • 15
  • Are you providing the service at component level or module level or root level? Also does all the components fall in same module? – sabithpocker Mar 12 '19 at 07:53

2 Answers2

2

You need to use pipe operator in Angular 6+ as follows instead of chaining:

Example -

getSomeData(): Promise < any > 
{
    if(this.data) // should keep service from doing extra http for the same request
    {
        return Promise.resolve(this.data);
    }
    else
    {
     return this.http.post(this.createURL('getData',{}),JSON.stringify({}), this.createGetOptions()).pipe(
                timeout(environment.timeout),
                share(),
                map((response: Response) => {
                    return response;
                })).toPromise();
    }
}

Also make sure you import share as follows:

import {share} from 'rxjs/operators';
TheParam
  • 10,113
  • 4
  • 40
  • 51
0

Take a look at my library ngx-RxCache. I wrote it exactly for this kind of thing.

https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • why would one need a library while it's a typical use case for rxjs and it was supported bu previous versions of angular ? – user7082181 Mar 18 '19 at 12:42
  • I wrote an article on the library here if you want an answer to that question https://medium.com/@adrianbrand/angular-state-management-with-rxcache-468a865fc3fb – Adrian Brand Mar 18 '19 at 20:31