How can I display the top 5 data results after subscribing in Nativescript?

Utilizing this function allows me to retrieve all my data from the web service.

 public data: Data[];
    getall() {
        this.ws.getalldata().subscribe(
            data=> {
                this.data= data;
            }
        );
    }

Here is a snippet from the Json file:

 {
        "StatusCode": 0,
        "StatusMessage": "OK",
        "StatusDescription": [
            {
                "id": "1",
                "id_type": 1,
                "desc": "TRTY",
                "active": 0,
                },
              ....
             {
                "id": "3",
                "id_type": 50,
                "desc": "qqq",
                "active": 0,
            },
            {
                "id": "4",
                "id_type": 50,
                "desc": "qqq",
                "active": 0,
            },
               ......
           {
                "id": "30",
                "id_type": 2,
                "desc": "hhh",
                "active": 0,
            }
          } 

To display this data in html, you can use the following code:

  <StackLayout *ngFor="let item of data">                
        <Label row="1" col="1" text="" class="list-group-item-text" [text]='item.id_type'></Label>
        <Label row="1" col="1" text="" class="list-group-item-text" [text]='item.desc'></Label>
     </StackLayout>

Now, I am looking for a way to display only the top 5 elements in the template. How can I achieve this?

Answer №1

According to the RxJs documentation, if you need to manipulate the 5 most recent items, you can achieve this in RxJs 6 with the following code:

import { concatAll, takeLast } from 'rxjs/operators';

public data: Data[] = [];
...

    this.ws.getalldata().pipe(concatAll(), takeLast(5)).subscribe(
        item=> {
            this.data.push(item);
        }
    );

Another way to accomplish this is by manipulating the array directly,

    this.ws.getalldata().subscribe(
        data=> {
            this.data = data.slice(-5)
        }
    );

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

Error encountered in Typescript while attempting to $set a subdocument key value in MongoDB

This is a sample data entry. { _id: ObjectId('63e501cc2054071132171098'), name: 'Ricky', discriminator: 7706, registerTime: ISODate('2023-02-09T14:23:08.159Z'), friends: { '63e502f4e196ec7c04c4 ...

The anticipated data type is derived from the attribute 'value' defined within the 'IntrinsicAttributes & ProviderProps<IProductContext>' type

During the creation of an e-commerce website, I decided to use React Typescript. However, I encountered an issue with Contexts while trying to export my state in the Provider value. Thank you for any assistance provided. ERROR Type '{ products: IP ...

Achieving a consistent scroll value using RxJs

I have a block with a mat-table inside, which has an initial scroll value of 0. I am trying to achieve a scenario where the scroll value changes automatically to 2 or more when you reach a height of 0 and again changes back to 2 when scrolled to the final ...

After reinstallation, Angular CLI is still not functioning properly

I recently tried to upgrade my Angular CLI by uninstalling it and installing the new version. However, I encountered an issue where I am unable to run ng commands anymore due to an error message that keeps appearing: ng : File C:\Users\Sirius&bso ...

Importing and declaring child components in Angular testing with Karma, Jasmine, and TestBed is essential for comprehensive component testing. This ensures all

Challenge Description: When writing unit tests using karma/jasmine for an angular component that utilizes other angular components, there is a need to recursively import all components included in child components into the testbed configuration. Is there a ...

Is there a way to retrieve the timezone based on a province or state in TypeScript on the frontend?

I've been working on an angular app that allows users to select a country and state/province. My current challenge is determining the timezone based on the selected state/province, with a focus on Canada and the US for now (expanding to other countrie ...

"Encountering issues with Angular2's FormBuilder and accessing nested object properties,

As I dip my toes into TypeScript and Angular2, I find myself grappling with a nested object structure in an API. My goal is to align my model closely with the API resource. Here's how I've defined the "Inquiry" model in TypeScript: // inquiry.ts ...

Injecting services and retrieving data in Angular applications

As a newcomer to Angular, I am trying to ensure that I am following best practices in my project. Here is the scenario: Employee service: responsible for all backend calls (getEmployees, getEmployee(id), saveEmployee(employee)) Employees components: displ ...

The Angular2 cli throws an error stating: "Cannot add a new entry to an existing one."

I have been utilizing the Angular2 Cli as my runtime environment for my Angular 2 application and I must say, I am thoroughly impressed by its architecture, top-notch development tools, and overall well-thought-out design. However, every so often, specifi ...

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

Rows in angular ag grid are vanishing when data is filtered

My ag grid includes custom components for each column, but I'm facing an issue where the components disappear when filtering the data. For example: the component inside the row To apply filtering, I use an input with a filtering function: <data-gr ...

"Utilize TypeScript to create a function that can handle either a single value or

I am attempting to develop a double function with the following structure: type MaybeArray<T> = T | T[]; function double<T extends MaybeArray<number>>(data: T): T extends number[] ? number[] : number { if (Array.isArray(data)) { / ...

TypeScript enabled npm package

I am currently developing a npm module using TypeScript. Within my library, I have the following directory structure: . ├── README.md ├── dist │ ├── index.d.ts │ └── index.js ├── lib │ └── index.ts ├── ...

Best practices for using useEffect to fetch data from an API_FETCH in a certain condition

When retrieving state from an API using Zustand within a useEffect function, what is the recommended approach to do so? Currently, my implementation is quite straightforward: export interface ModeState{ modes: Mode[]; fetchModes: () => void; } expo ...

Adding a new value to a string variable using TypeScript

Just starting out with Angular and I'm looking to capture user input from a text box with each keystroke and add it to a string variable like in Java. In my text box, I have the following setup for capturing key events: <input type="text" ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Trouble with ScrollView not scrolling on Nativescript-Vue

I am facing an issue with a scrollable view in my project. I have a list of items that should be scrollable, but for some reason it is not scrolling as expected. The structure involves a vertical stack layout wrapped in a scrollview, and inside the stackla ...

What is the internal mechanism used by Angular for routing implementation?

My traditional belief about web browsers has been challenged by the behavior of Angular. I used to think that when a user enters a new URL, the browser would fetch a whole new page from the network and display it, replacing the old one. But with Angular, ...

When the URL is entered manually, there appears to be some unusual behavior with Angular

Currently, I am in the process of developing a web application using Angular 7 for the frontend and NodeJS, MongoDB, and ExpressJS for the backend. The app functions as expected when I interact with it by navigating through, but there is an issue when manu ...

Ways to retrieve an image uploaded on a nestjs server

I am facing an issue with my NestJS server where I have uploaded images but cannot access them as they appear to be some unreadable data. I have tried converting them to a blob and then setting it as an object URL for the image tag, but that also did not w ...