Exploring Angular Factory: Creating the getAll method for accessing RESTful APIs

In my Angular.JS factory, I am retrieving data from a REST Api.

The REST Api endpoint is "/api/getSsls/1", where 1 represents the page number. The API response is in JSON format and contains the first ten items along with total pages/items information.

I'm trying to create a factory method that fetches all items from the API and iterates through all pages.

This is what I have attempted:

app.factory('Ssls', function ($routeParams,$http) {

allSsls = [];

return {
    list:
        function (page, callback) {
            return $http.get("/api/getSsls/" + page).success(callback);
        },

    listAll:
        function (ssl, callback) {
            var TotalPages = ssl.paging.TotalItems/ssl.paging.PageSize;
            TotalPages = Math.ceil(TotalPages);
            console.log("TOTAL Pages:" + TotalPages);

            for(var i = 1; i < TotalPages; i++ ) {
                this.list(i,this.processListAll(ssl));
            };
        },

    processListAll:
        function (data) {

            for( var j = 0; j < data.list.length; j++){
                console.log(data.list[j]);
                allSsls.push(data.list[j]);
            }
        }

Next, I invoke this factory method from the controller:

Ssls.list("1",function(data) {  
        var list = Ssls.listAll(data);
        console.log("ALL:" + list);
    });

I am facing a couple of issues:

  • The array "allSsls" (and "list" in the controller) appears to be empty, indicating a potential problem with variable scope.
  • The function "processListAll" only seems to iterate over the dataset of the first page, potentially due to an issue with the callback and parameter passed into it within the code line (this.list(i,this.processListAll(ssl));).

This is my first question on Stack Overflow. Thank you for your assistance!

Answer №1

Your current implementation includes Ssls.list() in your controller, utilizing a callback function. It is unnecessary to return the $http promise from your service. However, the issue lies in how you are invoking the callback function. Ensure that you correctly pass the data to it by following this revised approach:

list:function (page, callback) {
      $http.get("/api/getSsls/" + page).success(function(data){
        callback(data);
      });
 }

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

Issue with Chrome not triggering onMouseEnter event when an element blocking the cursor disappears in React

Important Note: This issue seems to be specific to Chrome Currently, React does not trigger the onMouseEnter event when a blocking element disappears. This behavior is different from standard JavaScript events and even delegated events. Below is a simpli ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...

Having trouble accurately obtaining the height of a DIV element using jQuery

After trying to troubleshoot on my own, I ran into a roadblock due to my specific requirements not being met by existing solutions. The issue at hand is as follows: I have a sticky DIV element positioned to the left, nested within another DIV Element wit ...

Is it possible to access the scope when the Angular-UI-Router is exited?

I'm searching for a potential solution: $stateProvider.state('user', angularAMD.route({ url: '/user/:id', templateUrl: 'views/user.html', controllerUrl: 'views/user', controller: ...

An error was encountered: SyntaxError - An unexpected token '!' was found

I am having trouble creating a react cluster map. I encountered a SyntaxError, and I'm not sure what went wrong. Initially, my map was working fine, but after using the use-supercluster npm package, it started showing an Uncaught SyntaxError: Unexpect ...

Utilize JavaScript to Replace KeyPress Event on Input Field

While attempting to substitute the key press of "K" with "Z" in an input field, I managed to accomplish it successfully. However, there seems to be a slight delay that causes the user to observe the transition from "K" to "Z". Below is the code that I use ...

What is the best way to include a &nbsp; in a map function using JavaScript?

A challenge I encountered while working in React is as follows: <Grid item> { rolePriorities.map((rp, index) => ( <Chip key={index} label={rp} color="primary" sx={{ color: "whitesmoke" }} /> ...

"Allow users to select only the year with Material-UI DatePicker

Is there a method to display solely years using the Material UI DatePicker component in React? I would like to enable users to choose only the year, excluding months or days. Please note that neither the openToYearSelection option nor the autoOk feature ...

Applying an AngularJS ng-repeat filter based on specified conditions

I am working with two arrays: items and items2. If items2 is empty, I want to display only the one item in items. Is there a way to add a conditional statement to the limitTo filter? The limitTo should be applied based on a certain condition. Appreciate ...

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

convert webpages and images to PDF with a custom watermark

Looking to convert images fetched from the server into PDF format with a watermark by clicking a button. It would be ideal if there is a plugin that allows for PDF preview with disabled user selection and copy options. The website's platform is Sales ...

Assign the value in the text box to the PHP session variable

Currently, I am developing a PHP "interactive text game" as a part of my assignment project. My task involves creating a user interface where users input information (such as character names) into text boxes that appear sequentially as they complete the p ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

Tips on transforming truncated surfaces into complete entities

When working in Three.js, I encountered a situation with a 3D object where local clipping planes were used to render only a specific part of the object. However, due to the nature of 3D objects being "hollow" (only rendering the outer surface), when somet ...

What is the best way to display a loading image and temporarily disable a button for 3 seconds before initiating the process of sending post data from another page via

Is there a way to display a loading image and disable a button for 3 seconds before sending post data from another page using AJAX POST? Once the OK button is clicked, I would like the loading image to appear and the <input type="button" value="Check" ...

Creating a modal dialog with AngularJS directive

My goal is to transfer a value from a button's data-id attribute to a modal dialog. This is what I have implemented: Button HTML <button ui-sref=".modal" btn-attr-click data-id="{{data.nip}}">Simulate</button> Angular State : var rout ...

Steps to partially open the Modal Sheet Swipe Step by default

I've set up a modal sheet component with the following structure: <f7-sheet class="myClass" style="height: auto" swipe-to-step :backdrop="false" > <div class="sheet- ...

Images cannot be shown until they have been uploaded

My issue involves a menu that loads an external file (form) on the same page, and for the menu, I am utilizing a specific function for menu styling. Custom Menu Function function getXmlHttp() { try { return new ActiveX ...

Setting up initial values for React properties

Below is the React code snippet I am currently working with: this.state = { colsHiddenStatus: new Map([['rowNumber',true], ['id', false], ['firstName', false], ['lastName', false], ['mobile', false], [&a ...