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

Unexpected lack of tree shaking in Angular AOT compiled application

I am developing a module called MyCommonModule that consists of common components, services, etc. This module is designed to be shared across multiple Angular applications. Here is an example of a basic app that imports MyCommonModule, without directly re ...

Attempting to locate a method to update information post-editing or deletion in angular

Are there any methods similar to notifyDataSetChange() in Android Studio, or functions with similar capabilities? ...

Determine the field's type without using generic type arguments

In my code, there is a type called Component with a generic parameter named Props, which must adhere to the Record<string, any> structure. I am looking to create a type that can accept a component in one property and also include a function that retu ...

The Angular error dialog triggered by the ErrorHandler fails to show any information when encountering a TypeError

I've managed to get a lot of this example up and running with help from other sources, but I'm still facing one lingering issue. When I deliberately throw an error, the Error Dialog functions as expected. It also works correctly when throwing an ...

Issue TS2339: The object does not have a property named 'includes'

There seems to be an issue that I am encountering: error TS2339: Property 'includes' does not exist on type '{}'. This error occurs when attempting to verify if a username is available or not. Interestingly, the functionality works ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

retrieve Angular data across components using Input

When using fetch to make a request to the reqres api users in app.component, I then share the data with its child component (hello.component) via Input. While I am able to get the correct user names in the child template, I encounter an issue when trying t ...

Incorporate FontAwesome icons into table headers within an Angular framework

I am attempting to customize the icons for sorting in my table headers by following the guidelines laid out in the ng-bootstrap table tutorial. The NgbdSortableHeader directive plays a key role in changing the sorting of columns: @Directive({ selector: ...

Issues encountered while attempting to update data in angular2-datatable

Once the datatable has been rendered, I am facing an issue where I cannot update the data. I'm utilizing angular2-datatable. In my appcomponent.html file: If I try to update 'data2' in my appcomponent.ts file as shown below: this.httpserv ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...

What could be the reason for the crash caused by ngModel?

The usage of [(ngModel)] within a *ngFor-Loop is causing an endless loop and crashing the browser. This is how my HTML looks: <div class="container"> <div class="row" *ngFor="let item of controlSystemTargetViewModel.values; let index = i ...

Find the TypeScript data type of an array that may be empty

Struggling to determine the TypeScript type of data being passed into my React component. The data could either be related to cats or dogs: my-component.tsx: export const MyComponent = { props: { data: any; // Ideally looking to utilize the union type & ...

When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript. My focus is on creating an abstract class with a single public method that invokes some private methods. Below is the simplified version of my TypeScript class: export ...

Navigating through pages using PHP

I'm fairly new to PHP and could use some guidance on this. Currently, I am working on a website using the Core CMS. My goal is to modify the functionality of the previous/next buttons so that they cycle through tags instead of entries. Tags are store ...

Upon executing the tsd install and tsd query commands, a message indicating 'no results found' was displayed

Whenever I run these commands in Git Bash on Windows tsd query angular-material tsd query angular tsd install angular angular-material I always receive the message ">> zero results" ...

The specified type 'MutableRefObject<HTMLInputElement | undefined>' cannot be assigned to type 'LegacyRef<HTMLInputElement> | undefined'

Consider the following simplified component : const InputElement => React.forwardRef((props:any, ref) => { const handleRef = React.useRef<HTMLInputElement|undefined>() React.useImperativeHandle(ref, () => ({ setChecked(checke ...

The module '@angular/core' could not be located in the '@angular/platform-browser' and '@angular/platform-browser-dynamic' directories

Attempting to incorporate Angular 2.0.0 with JSMP, SystemJS, and TS Loader in an ASP.NET MVC 5 (non-core) application. Encountering errors in Visual Studio related to locating angular modules. Severity Code Description Project File Line Suppr ...

Can you conduct testing on Jest tests?

I am in the process of developing a tool that will evaluate various exercises, one of which involves unit-testing. In order to assess the quality of tests created by students, I need to ensure that they are effective. For example, if a student provides the ...

invoke a specified function at runtime

I recently came across a useful library called https://github.com/ivanhofer/typesafe-i18n This library has the capability to generate strongly typed translation data and functions, as illustrated below. (the examples provided are simplified for clarity) e ...