Retrieving and storing successful response data in Angular JS using the $http service caching

My dataFactory is set up to retrieve posts in a simple manner:

dataFactory.getPosts = function () {
    if (this.httpPostsData == null) {
        this.httpPostsData = $http.get("http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page]=-1&filter[order]=ASC&filer[orderby]=date")
            .success(function (posts) {

            })
            .error(function (posts) {
                console.log('Unable to load post data: ' + JSON.stringify(posts));
            });
    }

    return (this.httpPostsData);
}

The controller interacts with the factory and I am aware that the posts are promises, so actions are taken upon success and regardless. Everything is working smoothly.

.controller('CardsCtrl', function($scope, dataFactory,
        $ionicSlideBoxDelegate, $stateParams) {

    var parentID = $stateParams.parentID;
    var keyIDNumber = $stateParams.keyID;

    $scope.card = [];

    var httpcall = dataFactory.getPosts()
        .success(function (posts) {
            $scope.card = dataFactory.getChildPosts(parentID, posts, keyIDNumber);

            $ionicSlideBoxDelegate.update();
        });

    // additional tasks ......
});

Now, I am attempting to cache the post data. However, when the controller is called for the second time, an error stating ".success is not a function" is returned. This issue likely arises from the fact that the posts have already been retrieved - but how can I handle this situation?

Answer №1

The reason for the issue is that you are not returning the $http.get itself, but instead returning the promise after both .success and .error methods have already been executed.

To resolve this problem, you have two options: either modify the controller to use .then when handling the return, or adjust the service to simply return the $http.get call without including .success and .error, leaving the controllers responsible for handling them.

If you opt to update the controller to utilize .then, remember to also update the .success function in the service to "return posts;" accordingly.

Answer №2

Have you considered enabling the cache option as true in your $http request? You can find an example implementation here:

You could try something similar to this...

angular.module('foo', [])

.factory('dataFactory', ['$http', function($http){

  var dataFactory = {
          getPosts: getPosts
      };

  function getPosts(){

    var url = "http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page]=-1&filter[order]=ASC&filer[orderby]=date"

    return $http({ cache: true, url: url, method: 'GET'})
      .error(function (posts) {
        console.log('Unable to load post data: ' + JSON.stringify(posts));
      });

  };

   return dataFactory;

}])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the concept of nested includes in sequelize?

Is it possible to perform a nested include in Sequelize? I have a table called products that has a one-to-many relationship with comments, and the comments table has a many-to-one relationship with the users table. Each comment has a user_id and product_id ...

Using the 'useMediaQuery' function from Material UI in a class component

Currently experimenting with Material UI's useMediaQuery feature to adjust the styles of a specific component, in this case the Button component. The objective is to eliminate the outline surrounding the button when the screen size decreases. The atte ...

Dealing with AngularJS ng-model problems when duplicating a form

Currently, I am facing an issue with sending parameters to control and require some guidance. I have multiple types of questions within the ng-repeat loop named 'question' that I am iterating through. The problem arises when there are two questi ...

Creating a JSON structure using an array in Typescript

Here is an example of my array structure: [ { "detail": "item1", "status": "active", "data": "item1_data" }, { "detail": "item2", "status": ...

effortlessly eliminate the Google MyMap watermark from an iframe using ReactJS

I am new to ReactJS and I would like help on how to hide the watermark on a Google My Map. Can someone please assist me with this? <iframe src="https://www.google.com/maps/d/u/1/embed?mid=1OMSkPKZi-U-CnmBr71zByNxp8HYi-vOc&ehbc=2E312F" fram ...

Tips for integrating the X-XSRF-TOKEN authentication method into an Angular2 application alongside a .NET Core application

I have successfully configured the antiforgery middleware in my .NET Core app by adding the necessary settings in Startup.cs: services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); within the ConfigureServices method, and ...

JavaScript: Efficiently Replacing Multiple Text Instances

To ensure that users do not input multiple empty paragraphs in the text editor, I have found a method to eliminate a single <p><br></p> from the text within the editor message. var str = content.replace('<p><br></p> ...

New project was successfully generated, but the information is missing when transmitted from React to Django API

I recently developed a React + Django application and implemented a basic CRUD feature. Everything was working smoothly until I encountered an issue while creating a project and storing it in the Django database. When I view the project at projects/list, o ...

Using json_encode with chart.js will not produce the desired result

I am attempting to utilize chart.js (newest version) to generate a pie chart. I have constructed an array that I intend to use as the data input for the chart. This is the PHP code snippet: <?php if($os != null) { $tiposOs = array('Orçamento ...

Firebug detected an error with the regular expression flag "h" after executing the YUI Compressor

When I run YUI Compressor, an error occurs with the message: invalid regular expression flag h [Break On This Error] ction(event){$(this).removeClass('lumi...cs_glb.php</b> on line <b>221</b><br/> The issue seems to be with t ...

Learn the art of blurring elements upon clicking in Vue

I've been attempting to trigger the blur event on an element when it is clicked, but I haven't been able to locate any helpful examples online. My initial approach looked like this: <a @click="this.blur">Click Me</a> Unfortunately, ...

"Enhance your Django website with a dynamic voting button using AJAX

I am working on a project where I have implemented the following code: (r'^oyla/(\d+)/$', oyla), Here is the view associated with this code snippet: @login_required def oyla(request, id): if request.is_ajax(): entry = Entry.ob ...

Having trouble with v-model not updating the data value on a dropdown in Vue.js?

When I set the initial value on the data property, the dropdown option is correctly displayed. However, if I select a different value from the dropdown, the data property does not update accordingly. <select class="form-control" ...

With vuejs, only one place can control the changing of v-model

Hello, I am currently working on integrating VueJS2 code with Laravel Blade. However, I have encountered an issue with the following VueJS2 code: new Vue({ el:'.add_item_to_price_menu', data:{ percentage:null, }, methods: ...

When text is wrapped within the <li> tag

In this div, the structure is as follows: <div class="box1" id="infobox"> <h2> Point characteristics: </h2> <div style="padding-left:30px" align="left"> <ul> <li class="infobox_list"><b>X value: </b>< ...

Keep the HTML video link out of sight in the Control Center on iOS devices

Looking for a way to conceal the video URL from appearing in the iOS Control Center, can anyone provide a JavaScript or HTML code solution? https://i.sstatic.net/NI79O.png ...

The ng-repeat directive adds an additional line after each iteration of the list item

Whenever the angular directive ng-repeat is utilized with an <li> element, I notice an additional line appearing after each <li>. To demonstrate this issue, see the simple example below along with corresponding images. Here is a basic example ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

transferring information between pages in nextjs

Currently in the process of developing a website, specifically working on a registration page for user sign-ups. My main challenge at the moment is validating email addresses without using Links. I need to redirect users to a new page where they can see if ...

Executing JavaScript Code Through Links Created Dynamically

I am currently developing a website with a blog-style layout that retrieves information from a database to generate each post dynamically. After all posts are created, the header of each post will trigger an overlaid div displaying the full article for tha ...