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

Changing the generic type's constraint type in TypeScript to have more flexibility

I have developed a utility type named DataType that takes in a parameter T restricted to the type keyof MyObject. When the key exists in MyObject, DataType will return the property type from MyObject; otherwise, it will simply return T. interface MyObject ...

Retrieving Identifiers with Typescript from an object

I'm a newcomer to Typescript and I'm looking to extract ids from an observable Here's the observable data: let myObj = [{ "id": 1, "text": "Mary" }, { "id": 2, "text": "Nancy" }, { "id": 3, "text": "Paul" }, { "id": 4, "tex ...

Issue with Async Pipe when connected to a recently generated observable is causing failures

Encountering an error when trying to use the Async Pipe with a newly created Observable? "Cannot read property 'subscribe' of undefined" Check out this Plunkr for a demonstration: https://plnkr.co/edit/vljXImCYoNubjyxOaWo3?p=preview If you com ...

"Enhancing User Experience with Hover States in Nested React Menus

I have created a nested menu in the following code. My goal is to dynamically add a selected class name to the Nav.Item element when hovering, and remove it only when another Nav.Item is hovered over. I was able to achieve this using the onMouseOver event. ...

Converting JSX files to TSX files: a step-by-step guide

I am facing an issue with this particular component on the website. It is currently in .jsx format while the rest of the website uses .tsx files. I need to convert this specific component into a .tsx file. Can someone provide assistance or guidance? Despit ...

Error: _CoalescedStyleScheduler provider not found

I'm currently attempting to follow a tutorial on Angular Material pagination, but I keep encountering this error: ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[MatTable -> _CoalescedStyleScheduler]: Static ...

Incorporating HTTP status codes into error handling

I have developed an API where I've organized the services separately from the controllers. In my service functions, I've included basic checks to trigger errors when certain conditions are met. Currently, my controller function just returns a 500 ...

Explore all user-defined properties of a specified type using the TypeScript Compiler API

Consider the following model structure: interface Address{ country: string; } interface Author{ authorId: number; authorName:string; address: Address; } interface Book{ bookId:string; title: string; author : Author; } I want to iterate th ...

Achieving TypeScript strictNullChecks compatibility with vanilla JavaScript functions that return undefined

In JavaScript, when an error occurs idiomatic JS code returns undefined. I converted this code to TypeScript and encountered a problem. function multiply(foo: number | undefined){ if (typeof foo !== "number"){ return; }; return 5 * foo; } ...

Exploring the incorporation of interfaces into Vue.js/Typescript for variables. Tips?

I have an interface:   export interface TaskInterface{ name: string description1: string time: string } and a component import { TaskInterface } from '@/types/task.interface' data () { return { tasks: [ { name: 'Create ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

"When a class extends another class and utilizes properties within a static property, it essentially becomes

I have been encountering challenges with generics in TypeScript for quite some time now. My current setup is as follows: First, there is a generic class defined as: class Entity { public static schema = {}; } Then, there is a class that extends the ...

How is babel-loader / tsc compiler able to distinguish between importing a package for its types only and for its functionalities?

Currently, I am integrating Typescript into my project. During this process, I made an interesting discovery. In the App.tsx file below, you will notice that I needed to use import firebase from "firebase/app" in order to access the firebase.ap ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Angular Pipe displays values properly, but ngFor fails to render them

I am using a pipe to filter my ngFor loop with exact matches that are passed through by clicking on the filter argument. Below is the code for my pipe: transform(values: any[], criteria: string, group): any[] { if (!values) { ...

What is causing this TypeScript error to be raised by this statement?

Can you explain why the following statement is throwing a type error? const x: Chat = { ...doc.data(), id: doc.id } The error message states: Type '{ id: string; }' is missing the following properties from type 'Chat': message, name, ...

Executing one controller function from another controller in Typescript

There are two typescript controllers in my project Controller A { public methodOfA() {//perform some action} } Controller B { public methodOfB() {//perform some action} } I am trying to implement the following functionality Controller B { ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document. The function is executed in a loop up to a value of 5. However, even though the function runs 5 times, the value of 'i' always reflects the last value. The ...