Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    caching with $http


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



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Man 1: 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.