This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

caching with $http

2:17 Angular 1.x lesson by

By default your HTTP requests with the $https service in Angular are not cached. By setting some options, you can turn caching on.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

By default your HTTP requests with the $https service in Angular are not cached. By setting some options, you can turn caching on.

Avatar
alex

Is there a way to access the $http.post data in the custom cache?
All our Ajax requests are on the same endpoint, and I want to be able to cache and clear cache based on the "action" param of the post data and not by the URL.

In reply to egghead.io

By default, HTTP requests are not cached, so if I load some people in here, you'll see that it loads the data and populates it. If I click again to load the people, it'll load it again and make the request again. Click again, it will make the request again, and so on and so forth.

To cache the data, the only thing you really need to do is pass in some options, where you say, "Cache is true." Then, if I refresh here, let me clear out all the script stuff that loaded. Once I click, "Load people," it will load it in and if I click "Load people" again, it's cached so it's not making another request out.

With this cache true, you can also provide your own custom cache, which I'll create here, so I'll say, "Factory," and we'll call this our "People cache." I'll just return a new cache factory, so cache factory. A cache factory for people.

If I inject this guy in here, so I use my people cache and then use that instead of true, this will work the same. I'll clear this out, click "Load people," loads once, and then doesn't load again. But this time it's using my people cache instead of the default cache factory.

What I'll do next is make it so that I can clear out the cache, so I'll just duplicate this and I'll say, "Clear cache." I'll say, "Clear cache here," and I'll come over here. To clear out the cache, I'll say, "Clear cache."

All I need to do is say, "People cache remove," and I'm going to remove this, which is the key to the data that loaded. If I paste it in and refresh, so clear this out. I'll load people and if I try and load it again, you'll see that nothing loads. If I hit "Clear cache," and then hit "Load people," you'll see that it loads again but now it's cached. If I try and click again, "Clear cache," "Load people," then you'll see that it loads again.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?