Transform the Angular function into a factory and take advantage of caching

My query differs from others with a similar title. I am attempting to transform a function into a factory in order to share data across controllers, but unlike my other factories, this one is not functioning as expected.

I have successfully implemented other factories within the same services.js file. When inspecting them in the console, they both display the same data, leading me to believe there may be an issue with the return statement.

This code operates correctly when placed directly in the controller:

Controller

getProgrammeData = function(activeProgrammeID) {
    var programmeData = [];
        var GetProgrammeData = Parse.Object.extend("Programme");
        var query = new Parse.Query(GetProgrammeData);
        query.equalTo("objectId", activeProgrammeID);
        query.first({
          success: function(object) {

                   $scope.programmes = {    
                      programmeTitle : object.get('programmeTitle'), 
                      id : object.id,
                      exerciseData : object.get('exerciseData')
                      };

          },
          error: function(error) {
            alert("Error: " + error.code + " " + error.message);
          }
        });
      }

However, this does not work as intended:

services.js

  .factory('parseQueryFactory', function($http) {
        return {
                getProgrammeData:function(activeProgrammeID) {
                var programmeData = [];
                var programmes = {};
                var GetProgrammeData = Parse.Object.extend("Programme");
                var query = new Parse.Query(GetProgrammeData);
                query.equalTo("objectId", activeProgrammeID);
                query.first({
                  success: function(object) {

                                programmes = {    
                              programmeTitle : object.get('programmeTitle'), 
                              id : object.id,
                              exerciseData : object.get('exerciseData')
                              };

                              console.log(programmes)

                  },
                  error: function(error) {
                    alert("Error: " + error.code + " " + error.message);
                  }
                })

            return programmes
        }
    }
    });

controllers.js

$scope.programmes = parseQueryFactory.getProgrammeData(activeProgrammeID);

Additionally, I would like to explore caching these results. How can I accomplish this?

Answer №1

The primary issue lies in the fact that you are initially returning an empty object and then creating a new object within the query callback, resulting in losing reference to that object. Consider implementing the following solution:

 .factory('parseQueryFactory', function($http) {
        var programmes = {}
        return {
                getProgrammeData:function(activeProgrammeID) {
                var programmeData = [];

                var GetProgrammeData = Parse.Object.extend("Programme");
                var query = new Parse.Query(GetProgrammeData);
                query.equalTo("objectId", activeProgrammeID);
                query.first({
                  success: function(object) {
                      programmes.programmeTitle =object.get('programmeTitle');
                      programmes.id = object.id;
                       programmes.exerciseData = object.get('exerciseData');

                  },
                  error: function(error) {
                    alert("Error: " + error.code + " " + error.message);
                  }
                })

            return programmes;
        }
    }
    });

Answer №2

Expanding on @JesusQuintana 's response.

My approach to organizing a factory is as follows:

.factory('parseQueryFactory', ['$http', parseQueryFactory])

function parseQueryFactory($http) {
    var service = {
        getProgrammeData: getProgrammeData
    };

    var serviceBase = '/api/someController';

    return service;

    function getProgrammeData(activeProgrammeID) {
        return $http.get(serviceBase, { params: { activeProgrammeID: activeProgrammeID }).then(function (data) {
            return data.data;
        }).catch(function (message) { console.error(message); });
    }
}

This method simplifies the process for me in understanding a) the capabilities of this service, and b) the functionalities within the main function. For instance, everything preceding the return statement defines the core service and acts as a singleton. Conversely, the subsequent code consists of implementations that support my service's operations.

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 simplest method to check for the presence of a value within an object when utilizing lodash or angularjs?

I'm encountering an issue where this code works perfectly if "obj" is a collection, but falls short when trying to determine if a value exists within a single object. What would be the most efficient approach, utilizing either lodash or AngularJS, to ...

Using TypeScript to sort objects based on keys and convert an array of objects into a different object type

I'm facing an issue where I need to filter the objects within an array of objects based on keys and convert them into a different type of object. I attempted to solve it like this... const values = Object.keys(user).map((key) => {'refKey' ...

Add unique content to a div upon page reload

Whenever the page is refreshed, I would like to add a random anchor from an array into a specific div. Here's my current code: <div id="exit-offer" class="exit-offer-dialog"> <div class="offer-content" id="banner-load"> <bu ...

Tips for sending an input file to an input file multiple times

As a developer, I am facing a challenge with a file input on my webpage. The client can add an image using this input, which then creates an img element through the DOM. However, I have only one file input and need to send multiple images to a file.php i ...

"Upgrade your upload experience with Express Upload - easily switch out images in a folder while simultaneously

As I work on incorporating a profile picture feature into my website, I am encountering an issue where a newly uploaded image [newimg] with the same name as a previously uploaded image [oldimg] ends up replacing the older file in my directory. This results ...

Admin-on-rest sidebar navigation menu

Hello everyone! I am new to ReactJS and admin-on-rest. I am currently studying from this documentation and I am interested in creating a navigation submenu similar to the one shown here. I have tried searching on Google but haven't found what I need. ...

Unable to successfully add a property to an object within a collection managed by Sequelize

While working on a code similar to this one, I encountered an issue where adding a property doesn't work as expected. router.get('/', async (req, res, next) => { let produtos = await produto.findAll(); for(let i = 0; i < pro ...

The functionality for making a GET request in a React Component is not functioning as

I have successfully imported the axios library and React. In a React component, I am making a GET call which is returning a response like this: {"functionality": [ {"category": "", "price": 2.0, "moltiplicator": 100.0, "name": "Plat"} ] } How ...

transferring a delicious cookie to the browser

I have successfully integrated a basic login system using angular, express, and passport.js into an existing project by following the file structure and coding standards provided in angular-passport. Currently, users can sign up and log in without any iss ...

Unable to transform socket.io event into Bacon EventStream

After successfully binding the event on socket.io, the following code was executed: io = require('socket.io')() io.on 'connection', (socket) -> console.log socket.id io.listen 3000 An attempt was made to convert the socket.io ...

Locate a specific class inside a div and switch the CSS style to hide one element and reveal another

I have two divs, each containing a span. By default, the display of each span class is set to none. My goal is to toggle the display property of the span within the clicked div. If the span is already visible, I want to hide it; if it's hidden, I want ...

Bootstrap 4 Date Selector

Is there a different option I can use instead of 'datepicker' because it doesn't seem to be working correctly and I've heard it's not compatible with bootstrap 3+. When I paste the example datepicker code into a blank HTML page, i ...

Transmit information across disparate components in Vue.js

This situation involves a Graph component displayed in the body of the page, allowing user modifications. Additionally, there is a Search component located in the header of the page. These two components are independent - Graph is exclusive to the body o ...

Bringing Vue Components Together in Laravel: A Guide to Component Importation

Recently, I started learning Vue.js and I am looking to understand how to use component. Unfortunately, when I attempted to import my component into another component, it didn't work as expected. The framework I am currently using is Laravel 5.8 and I ...

Display the hidden element using jQuery with the !important rule

There is a specific element that has been given a class with the following CSS styling: .cls { display:none !important; } Despite attempting to display this element using jQuery $(".cls").show(); This method does not seem to be effective. Is ...

Component for numbering pages, utilize array mapping to locate route

I'm currently working on creating a component for page numbers using an array of objects that includes a path and an ID. import React from 'react'; export function PageNumber(props) { const pageData = [ {path: '/calc/1', id:1}, ...

Adjust the width of the element to match the size of the image within

My webpage features an image along with some accompanying metadata that I want to be centered on the page. I want the div holding the metadata to be the same width as the image. Here's an example: Unfortunately, I am unable to determine the image&apo ...

The unique text: "User-defined input element disregards changes initiated through

I created a custom input component that functions correctly, but I have encountered an issue. When I attempt to update the value through a method, the model gets updated but the input value remains unchanged. Here is my component: https://codepen.io/ken-r ...

Search for specific parameters in an array and retrieve them

I have been attempting to sift through an array of data retrieved from my API, but unfortunately, the data remains unfiltered. I suspect that it might be due to the way I implemented my method or perhaps my params are not being returned correctly. Below ar ...

Guide on implementing Regular Expressions in Directives for validation in Angular 8

Managing 8 different angular applications poses its unique challenges. In one of the applications, there is a directive specifically designed for validating YouTube and Vimeo URLs using regular expressions. Unfortunately, once the RegExp is declared, ther ...