Reputation: 364
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'
Upvotes: 1
Views: 438
Reputation: 10571
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';
Upvotes: 2
Reputation: 21658
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
Upvotes: 0