Creating an endless scrolling feature with Ionic 3

My tech stack includes symfony3 and FosRestBundle for the backend, and Ionic 3 for the frontend development.

While attempting to implement an InfiniteScroll feature following the Ionic documentation, I encountered an issue where only the loading text and spinner were displayed without any data being fetched.

The backend action looks like this :

/**
 * @Rest\Get(
 *     path="/articles",
 *     name="api_article_list"
 * )
 * @Rest\QueryParam(
 *     name="limit",
 *     requirements="\d+",
 *     default="5",
 *     description="Maximum element per page"
 * )
 * @Rest\QueryParam(
 *     name="offset",
 *     requirements="\d+",
 *     default="0",
 * )
 * @Rest\View(StatusCode=201, serializerGroups={"list"})
 *
 */
public function listAction(Request $request, ParamFetcherInterface $paramFetcher)
{

    $em = $this->getDoctrine()->getManager();

    $articles = $em->getRepository('AppBundle:Article')->findBy(
        array(),
        array('id' => 'desc'),
        $paramFetcher->get('limit'), $paramFetcher->get('offset')
    );

    return $articles;
}

As for the TypeScript code :

export class NewsPage {

results = [];
moreData = [];

constructor(public navCtrl: NavController, private http: Http, public loadingCtrl: LoadingController) {
    this.getData();
}

getData() {
    this.http.get(Globals.baseUrl + 'articles?limit=' + this.limit +'&offset=' + this.offset )
        .map(res => res.json()).subscribe(data => {
        this.results = data;
    });
}

loadMoreData() {
    this.http.get(Globals.baseUrl + 'articles?limit=' + this.limit +'&offset=' + this.offset )
        .map(res => res.json()).subscribe(data => {
        this.moreData = data;
    });
}

doInfinite(infiniteScroll) {
    this.offset += 2;

    this.loadMoreData();

    setTimeout(() => {

        infiniteScroll.complete();
    }, 500);
}

The HTML code is as follows:

<ion-card *ngFor="let result of results; let i = index">
   <ion-item> {{result.id }}</ion-item>
//............
</ion-card>

<ion-infinite-scroll (ionInfinite)="doInfinite($event)">

  <ion-infinite-scroll-content loadingSpinner="bubbles"
      loadingText="Loading more data...">
    </ion-infinite-scroll-content>
</ion-infinite-scroll>

Answer №1

Issue Resolved

dataList = [];
range: number = 5;
start: number = 0;

//****

fetchData() {
    this.http.get(Globals.baseUrl + 'articles')
        .map(res => res.json()).subscribe(data => {
        this.dataList = data;
    });
}

loadNextSetOfData() {
    this.http.get(Globals.baseUrl + 'articles?limit=' + this.range + '&offset=' + this.start)
        .map(res => res.json()).subscribe(data => {
        for (let item of data) {
            this.dataList.push(item);
        }
    });

}

updateInfiniteScroll(infiniteScroll) {
    this.start += 5;
    setTimeout(() => {
        this.loadNextSetOfData();
        infiniteScroll.complete();
    }, 500);
}

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

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

Encountered an issue: The type 'Usersinterface' is not meeting the document constraints

Below is a screenshot displaying an error: https://i.stack.imgur.com/VYzT1.png The code for the usersinterface is as follows: export class Usersinterface { readonly username: string; readonly password: string; } Next, here is the code for users ...

``Changing the value of a class variable in Angular 2 does not result in the

I am facing an issue with a component that contains a variable called myName export class ConversationComponent implements OnInit { private myName: string; showNames(name) { this.myName=name; } } The value is assigned using the showNames() m ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

What is causing the reluctance of my Angular test to accept my custom form validation function?

I'm currently facing an issue with testing an angular component called "FooComponent" using Karma/Jasmine. Snippet of code from foo.component.spec.ts file: describe('FooComponent', () => { let component: FooComponent let fixture ...

When defining functions in Typescript, the new() syntax is used

Can you explain the purpose of the type declaration for dialogComponent in this specific Typescript code snippet? createDialog(dialogComponent: { new(): DialogComponent }) : Promise<ComponentRef<DialogComponent>> { ... } (Referenced from ...

The Reactive Form is throwing an error: "Unable to access property 'controls' of undefined."

My attempt to create a reactive form with the Nested Form concept in Ionic 3 is encountering an error: 'Cannot read property 'controls' of undefined'. I would appreciate any assistance in resolving this issue. I have tried troublesh ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Organize and display a list of contacts alphabetically by the first letter of their

I have a list of contacts that I need help with. Despite searching on Stack Overflow, I couldn't find the answer. Can someone please assist? Thank you. export const rows = [ { id: 1, name: 'Snow', email: 'Jon', co ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

The React hook useState is struggling to accurately map array objects

Recently, I encountered an issue with a form that sends an array of objects to another React Functional Component: import React, { useState } from 'react' import uuid from 'uuid/v1'; const NewMovieForm = ( {addMovie }) => ...

Create a Typescript type extension specifically designed for objects with nested arrays of objects

After stumbling upon this inquiry, I am eager to adjust my code in a similar fashion, utilizing typescript and a more intricate object. Consider the type below: export type ImportationType = { commercialImportation: boolean dateToManufacturer: string ...

The problem of package related to scrolling header in Ionic arises when building with the `--prod` flag (Remember to include a @NgModule annotation

Hey there! I stumbled upon a package in the git repository that seems to have everything set up for compatibility with AOT. However, when attempting to build my app using the ionic build --prod command, the AOT build encounters an error as displayed below. ...

How can I pass DOCUMENT in Angular?

In my directive, I use dependency injection to access the DOCUMENT and set up an event listener: constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit() { this.document.addEventListener('click', this.clicked, true); } @Bound ...

Dealing with undefined arrays in Angular across multiple templates: Best practices

I'm currently developing a search screen for an application and I've come up with three possible outcomes for the results section. If the user hasn't searched yet, then show nothing. If the user searches and the array is empty, display "no ...

Using Angular and Typescript to implement a switch case based on specific values

I am attempting to create a switch statement with two values. switch ({'a': val_a,'b': val_b}){ case ({'x','y'}): "some code here" break; } However, this approach is not functioning as expected. ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

Tips on resolving handlebars 'module not found' error in typescript while compiling to umd

In my client-side JavaScript library written in TypeScript, I am attempting to incorporate Handlebars. However, when I try to import using import * as Handlebars from 'handlebars', I encounter an error message stating that TypeScript "cannot find ...