Guide on fetching and adding information with a single web API call in AngularJS

In this code snippet, I am utilizing the "$http.get" request to fetch data from a Web API in Angular.js.

The API URL includes a parameter called "pageNo=" which requires a digit to be added at the end in order to retrieve data for a specific page number. This is done to manage heavy request loads, with each page containing 10 records.

I have defined a scope variable ($scope.pageCount) and passed it along with the URL. This approach works well as it allows me to fetch 10 records at a time.

Now, the next challenge is to load more data on scroll down (similar to using an infinite-scroll feature) and append it to the existing list of data.

Is there a way to retrieve additional data from the same request? I have integrated 'infinite-scroll' into the application and receive an alert when scrolling down.

Below is the current function that is operational:

app.controller('SpotLightCtrl', function ($scope, $http, shareEventID) {

    $scope.pageCount = 1;
    $http.get("https://stg.myapi.svc/pageNo="+$scope.pageCount+)
      .then(function (response) {
          $scope.data = response.data;

          $scope.loadMore = function () {
              alert('Load more records');
          };

      });

});

Below is the HTML code:

<div class="content-block spotlight-listing" ng-controller="SpotLightCtrl" infinite-scroll='loadMore()' infinite-scroll-distance='1'>
    <h1>Spotlight</h1>
    <div ng-repeat="event in data.eventList" class="deals-block">
        <div class="col-md-4 col-xs-12 img-style">
            <a href="/SpotLight-Detail"><img ng-src="{{event.eventPosterImage}}" class="img-responsive img-rounded" /></a>
        </div>
    </div>
</div>

If any part of this explanation is unclear, please let me know. Any assistance would be greatly appreciated...

Answer №1

To streamline the http call, consider placing it within a function that can be invoked with the desired page count parameter.

app.controller('SpotLightCtrl', function ($scope, $http, shareEventID) {

 $scope.pageCount = 1;
 $scope.data = [];
 function fetchData() {
    $http.get("https://stg.myapi.svc/pageNo=" + $scope.pageCount)
        .then(function (response) {
            $scope.data = $scope.data.concat(response.data);
        });
 }

 $scope.loadMore = function () {
    console.log('Loading more records');
    ++$scope.pageCount; // Increment page count by 1
    fetchData();
 };

 fetchData();
});

By calling the loadMore function, the page count is increased by one and additional records are appended to $scope.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 updating Three.js Mesh position

I have been working on mapping lat/long data to a sphere. I am successfully generating vectors with different positions and setting the cube mesh position accordingly. However, when I merge and display the cubes, it seems like there is only one cube show ...

Determine whether the JSON object has been declared

Having trouble determining if the value of values[item]['total'] is defined in a JSON object. The variable item is obtained from the select box value and I am attempting to use an if-else statement to check if values[item]['total'] is ...

What is the process for obtaining the distribution version of an AngularJS project?

After attempting to create the distribution version of my project using the command gulp, I realized that although it successfully built, I encountered issues when trying to run it in the browser. Interestingly, my friend was able to complete the same pro ...

Error: The database has encountered a duplication error in the followers index of the MERNSM.users collection, with a duplicate key value of undefined

Encountered a MongoServerError: E11000 duplicate key error collection: MERNSM.users index: followers_1 dup key: { followers: undefined }. This is puzzling as there is no unique constraint set in my schema. I am unsure of what could be causing this issue, e ...

Optimal approach for organizing a mysql+nodejs+express application

In my development process, I typically utilize mysql without sequelize. To establish the database connection, I usually create a module.export function that can be required in other files. Here's an example: var db; module.exports={ getConnection = f ...

The text box remains disabled even after clearing a correlated text box with Selenium WebDriver

My webpage has two text boxes: Name input box: <input type="text" onblur="matchUserName(true)" onkeyup="clearOther('txtUserName','txtUserID')" onkeydown="Search_OnKeyDown(event,this)" style="width: 250px; background-color: rgb(255, ...

Instead of storing the result in a variable, return the value directly in Angular2

This particular code snippet is designed to load a JSON file asynchronously and place the result into the variable _values. private getValue(name) { this.http.get('http://localhost:8080/getValue/' + name) .subscribe(res => this._values = re ...

Is there a way to temporarily deactivate radio buttons for a specific duration after they have been selected?

Hello everyone, <input type="radio" value="LOVE" onclick="toggle(this.value)">LOVE <br> <input type="radio" value="INDIFFERENT" onclick="toggle(this.value)">INDIFFERENT <br> <input type="radio" value= ...

Conceal a card once verified within a bootstrap modal upon successful AJAX completion

On my delete page, there are multiple posts with a delete button. When the delete button is clicked, a Bootstrap modal opens asking for confirmation "Are you sure you want to delete this post? YES : NO" If the YES button is clicked, the .click(function(e) ...

Having trouble navigating with router.navigate and utilizing local storage?

I have a code that utilizes router.navigate to direct the user to a specific location abrirLista(categoria, id) { localStorage.setItem('categName', JSON.stringify(categoria)); const slug = slugify(categoria); this.router.navigate(['/lista&ap ...

Echarts: scatter plots linked with a line to the axis (resembling the PACF diagram)

I am currently working with echarts (js). Is there a method to link the dot of the scatter plot with the 0 value on the y-axis? I want it to resemble a pacf plot, similar to this example: The desired outcome should look something like this: https://i.sta ...

Handling an Express server that receives a request with no data

I'm struggling with a problem where I am unable to retrieve a basic JSON object. When I log it to the console, all I see is {}. Let me showcase the server code below: const express = require("express"); const app = express(); app.listen(3000); app.us ...

Creating a State in Typescript Vuex with Accessors: A Step-by-Step Guide

Within the vuex store, I am attempting to initialize a state called _token. However, when I try to access the property within the same class, I am encountering an error message stating that the setter for _token is not defined. Can anyone shed light on why ...

Submitting a form within AJAX-powered tabs (using the Twitter Bootstrap framework)

I have encountered an issue while trying to submit a form that is located within tabs. The content of these tabs is generated through AJAX. My problem arises when I submit the form - the page refreshes and loads the "default" tab, causing the PHP function ...

Guide on embedding internet audio onto an HTML webpage

I'm currently working on adding sounds and music to my program. The code that I have works perfectly when the audio files are downloaded onto my computer. However, I am looking for a way to play these sounds directly from the internet without needing ...

The error message UnhandledPromiseRejectionWarning: TypeError: crypto.subtle.digest is throwing an error as it is

Encountering an error message saying "crypto.subtle.digest is not a function" when running unit tests using Jest for a function that utilizes crypto.subtle.digest(), have attempted to resolve the issue while using JSDOM with no success: 1. `[Utilizing J ...

Mongoose is having trouble identifying the 2dsphere index I created

I am currently attempting to add a 2dSphere index for the field startLocation within the tourSchema. This is how it is defined: startLocation: { type: { type: String, default: 'Point', enum: ['Point'] ...

Guide: Implementing material-ui theme with redux in gatsby

I'm currently utilizing the material-ui theme in conjunction with redux-toolkit within a gatsby project. This is my theme.ts file: import { createMuiTheme } from "@material-ui/core"; import { useSelector } from "react-redux"; import { State } from ". ...

Reading the fixture JSON file in Cypress - A step-by-step guide

I'm struggling to read data from a JSON fixture file in Cypress for my test cases. Despite following various instructions and examples, I can't seem to make it work. Any ideas on what I might be doing wrong? Below are the details of my files alo ...

I'm struggling to grasp the reason behind the error message stating that x is not a function

Can someone help explain why I keep getting the error message "5Style is not a function"? NationalLevelCategoriesChosenList = [ ["5Style", "5MelodyHarmony", "5RhythmTempo", "5TextureStructureForm", "5Timbre"] ], [ [] ]; if (NationalLevelCategoriesC ...