Thịnh Phạm
Thịnh Phạm

Reputation: 2673

Prevent same requests from being sent simultaneously when using Angular resource

I have a few components in one page.

Each of them fetches the same data from the server.

As a result, when the page loads, these components send the same request multiple times.

Is there any way to prevent this? Like caching the promise of the first request and returning that to the next coming requests (before the promise resolved)?

Upvotes: 0

Views: 790

Answers (2)

Enzey
Enzey

Reputation: 5254

When calling the $http service you can additionally supply a cache object. If you do so any additional requests will use the cached value. If the same cache is used then additional requests made before the first is resolved will not call the server but wait for the response.

$http.get(url, {cache:cacheObj})

Where cacheObj is from $cacheFactory

Upvotes: 0

Divyanshu Maithani
Divyanshu Maithani

Reputation: 15036

In order to make sure that the request is sent only once, you can keep track of the first HttpPromise you create, and on subsequent calls of the function, return that same promise.

This SO link might be what you're looking for.

Upvotes: 1

Related Questions