Angular2 and ReactiveX: Innovative Pagination Strategies

Currently, I am diving into the world of ReactiveX. To make things easier to understand, I have removed error checking, logging, and other unnecessary bits.

One of my services returns a collection of objects in JSON format:

getPanels() {
    return this.http.get(this._getPanelsUrl)
        .map(panels => <Panel[]> panels.json());            
}

My component invokes this service method and stores the received data in an array:

panels: Panel[] = [];

ngOnInit(){
    this._PanelService.getPanels()
        .subscribe(data => this.panels = data);  
}

The objective is to show this data grouped in my template:

<ol>
    <li *ngFor="#panel of panels">
      <h3>{{panel.startDate}}</h3>
    </li>
</ol>

Now, I am interested in implementing pagination and displaying only three or four panels at a time.

Initially, I thought of using bufferCount to emit objects in groups:

getPanels() {
    return this.http.get(this._getPanelsUrl)
        .map(panels => <Panel[]> panels.json())
        .bufferCount(3,3);
}

As a result, I now have a multidimensional array, hence I need to update the component accordingly:

panels: Array<Panel[]> = [];

ngOnInit(){
    this._PanelService.getPanels()
        .subscribe(data => this.panels = data);
}

To my surprise, instead of a nicely organized array with each index containing three members from the collection, the entire collection is now stored in data[0]. So, I attempted reordering the sequence of operations:

getNextPanel() {
    return this.http.get(this._nextPanelUrl)
        .bufferCount(3,3)
        .map(res => <Panel[]> res.map(r => <Panel> r.json()));
}

Well, it seems like I am in deep waters now. Judging by my lambdas and code structure, it's evident that the data flow might get halted midway without reaching the component. At this point, I started questioning whether I really need to adhere strictly to the ReactiveX approach.

Next, I decided to attempt iterating through values in Angular itself. I experimented with some variables using the slice pipe:

<ol>
    <li *ngFor="#panel of (panels | slice:start:items)">
        <h3>{{panel.startDate}}
    </li>
</ol>
<button (click)="start = start + start"></button>

Despite being aware that Angular 2 is still in beta, I found myself stumbling as the parser kept flagging me for misusing operators and expressions where they weren't supposed to be. It was clearly a sign of my growing fatigue.

I am willing to learn from these missteps and embrace bigger challenges in the future. Do you have any advice or suggestions?

[EDIT]

Ultimately, I opted to utilize ng2-pagination as it precisely meets my requirements. Although it provides a working solution, I refrained from marking it as the answer since I am determined to try and implement the functionality using rxjs.

If you have reached this point and are seeking a functional solution, give ng2-pagination (currently in beta 2) a shot as it works quite effectively.

Answer №1

Apologies for the delay, but I believe this solution could be beneficial to others facing a similar issue.

The issue with your current implementation may lie in the fact that the this.panel variable is being overwritten during each onNext event on the subscriber.

To address this, consider making the following adjustment:

getPanels() {
  return this.http.get(this._getPanelsUrl)
    .map(panels => <Panel[]> panels.json())
    .bufferCount(3)
    .toArray();
}

Afterwards:

panels: Panel[][] = [];
ngOnInit(){
    this._PanelService.getPanels()
      .subscribe( data => { this.panels = data } );
}

The intention here is to consolidate all onNext events into an array (using the toArray method) that will be emitted as a single onNext of a new Observer, encompassing all events.

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

Responding to ipcMain events within Spectron

I created an electron application that initiates a launcher window (in a renderer process) first, which then starts multiple background services. Once these background services are successfully started, it sends the message "services-running" on its ipcRen ...

Tips for integrating TypeScript files into Next.js HTML files

Encountering an issue while trying to load a typescript file from HTML, resulting in this error Here is the code snippet for the page: export default function Home() { return ( <> <Script src="/static/main.tsx"></Scri ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...

Examining interconnected services' dependencies

Looking to test out AService, which has dependencies on BService and CService. The dependency chain looks like this: AService --> BService --> CService The constructor for AService is as follows: constructor( private bService: BService ) {} The ...

Just a straightforward Minimum Working Example, encountering a TypeScript error TS2322 that states the object is not compatible with the type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

Currently, I am immersed in a project involving React and Typescript. I am grappling with error code TS2322 and attempting to resolve it. Error: Type '{ submissionsArray: SubmissionProps[]; }' is not assignable to type 'IntrinsicAttributes ...

What could be the reason for the absence of the observable item value appearing in the HTML template?

Working with Angular4, I recently created a straightforward list-details example. However, when attempting to display item details on the details page, specifically for items of Observable type class, I encountered some obstacles. Below is the snippet of c ...

Techniques for a versatile class limited to a particular category

In my code, I have a Vector class that looks like this: class Vector<N extends number> {...} N represents the size or dimension of the vector. This Vector class also includes a cross product method to calculate the cross product between vectors: cro ...

I'm seeing an issue where my SafeResourceUrl is being displayed as undefined within a function of the identical class

export class ClassName implements OnInit { url: string = "{{'content.url' | translate}}"; urlSafe: SafeResourceUrl; constructor(public sanitizer: DomSanitizer, private translate: TranslateService) { } ngOnInit() { ...

The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API. export class ListaGifsComponent { gifs : Object[] = []; urlBase = "http://api.giphy.com/v1/gifs/search?q="; termoPesquisado = "ryan+gosling"; key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn"; ...

Updating state in React without providing a key prop is a common issue, especially when

Currently, I am working on implementing a Radio Group where I want the radio button's checked value to update when another button is clicked. In the example provided below, it seems that the desired effect can only be achieved using the "key" prop. Is ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

What is the best way to emphasize specific months and years in an Angular Material datepicker?

I have an array of days, which can be from any year. I am attempting to customize the Angular Material datepicker to highlight specific months and years in the selection views based on the array of days. .html <input [matDatepicker]="picker" ...

Tips for creating ternary operator logic that account for numerous conditions and optional parameters:

Trying to create a logic for my validator functions that involves using objects as errorMaps for input validation. In the code snippet provided, args.drugName is an optional field. If the user provides text, we want to ensure it is greater than 3 letters; ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

invoking a function in one component from another component within an Angular 4 project using ng-smarttable

Utilizing ng-smarttable to display data in a table and have successfully added a custom button in a separate component. However, I am encountering an issue where the data does not reload when clicking on the button. An error message is appearing: ERROR Ty ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Is it possible to implement websockets with inversify-express-utils?

We are attempting to integrate websockets into our typescript application built on inversify-express-utils, but so far we have had no success: import 'reflect-metadata'; import {interfaces, InversifyExpressServer, TYPE} from 'inversify-expr ...

Scanning barcodes with Angular using a gadget

Currently in the process of integrating barcode scanning into my Angular project. I have already installed @zxing/ngx-scanner, however, I have noticed that the performance is not up to par and it doesn't seem to work with an external scanner device - ...

Is there a way to pre-load the content ahead of the footer?

My footer appears before the content is fully loaded. In my navbar, I have multiple buttons that open new components when clicked. When a user clicks on an event, it emits after the event data is loaded from the API and the footer loads correctly at that t ...