Tips on sorting through an array using Angular 11 and data

I'm working on a subpage that contains a large amount of detailed data in the form of thousands of records. I want to filter this data based on the "id" from my route, which is also included in the dataset. However, I've run into some difficulties while attempting this. I've tried various methods, starting from using ngIf and going through the .filter function, but all attempts have resulted in errors. The specific error message being:

Cannot read property 'filter' of undefined.

component.ts

export class ZawPgee2020Component implements OnInit {
    zawpl: Array<any>;
    zawplfiltered: Array<any>;
    rider: Rider;
    detailrider: DetailRider;

    constructor(private _speedwayService: SpeedwayService, private orderPipe: OrderPipe, private route: ActivatedRoute) {
        this._speedwayService.getZawpl()
            .subscribe(response => {
                this.zawpl = orderPipe.transform(response, "ZAWODNIK");
                });
    }

    getFilterData() {
    const zawplfiltered = this.zawpl.filter(zawpl => {
        return zawpl == this.rider.id;
        });
    }
}

service.ts

getRider(id) : Observable<any> {
    return this._http
        .get<any>("http://node.gurustats.usermd.net:60519/pgee2020")
        .pipe(
            map(result => result.data.filter(p=> p.id == id)[0])
      );
}

getZawpl() {
    return this._http
        .get("http://node.gurustats.usermd.net:60519/zawpl")
        .pipe(
            map(res => res ['data']))
}

component.html

<tr *ngFor="let detailrider of zawplfiltered | orderBy: order:reverse; let i = index">
    <td>{{ detailrider.ZAWODNIK }}</td>
</tr>

Answer №1

When retrieving data from an API, there may be a delay in receiving the information from the server to populate the zawpl variable. To prevent the zawpl array variable from being undefined, it is recommended to adjust your getFilterData() function and utilize the ternary ? operator:

Give This a Try

Within the component.ts file

getFilterData() {
const zawplfiltered = this.zawpl?.filter(zawpl_ => {
    return zawpl_ == this.rider?.id;
 });
}

Best of luck! Let me know if this solution works for you!

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

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

Unable to render a stationary image located within the component's folder in Angular

Within the components directory, I have placed an image file. It's a simple PNG with a logo on it. The four files in the directory are: blobb.png blobb.comp.ts blobb.comp.html blobb.comp.scss In the HTML file, I included the image using a static so ...

Is it possible for TypeScript to automatically determine the type of an imported module based on its path?

I'm currently working on creating a function, test.isolated(), which wraps around jest.isolateModules. This function takes an array of strings representing the modules to be imported, along with the usual arguments (name, fn, timeout), and then inject ...

Including a CSS link in a .css file is an essential step in styling

Can someone guide me on how to reference the Bootstrap link (https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css) in a .css file within an Angular project? ...

One-liner in TypeScript for quickly generating an object that implements an interface

In Typescript, you can create an object that implements an interface using a single expression like this: => return {_ : IStudent = { Id: 1, name: 'Naveed' }}; Is it possible to achieve this in just one statement without the need for separate ...

One of the essential components in Angular is currently absent

After integrating Angular4 with Visual Studio 2017 following the steps outlined in this article, I realized that my setup also involved using Nodejs 8.6.0 and npm 5.4.2 - which were the latest versions at the time. Despite having vs2017 generate a fold ...

What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

Error in Vuetify 3.1.2 with Vue 3 and TypeScript: Unable to assign type 'boolean' to type 'never'

I am currently building a project using Vue 3 (version 3.2.45), Typescript (version 4.9.4), and Vuetify (version 3.1.2). When working with Vuetify components, I often encounter situations where I need to pass specific props for styling, positioning, or ma ...

When using Angular forms, the password or username may be duplicated if entered twice when pressing the

I am currently working on a basic username and password form using Angular. Here's the template I have: <label class="welcome-content">Username:</label> <input #userName type="text" id="txtLoginUsername" (keyup.enter)="loginUser(userNa ...

Structured similar to a map with typed elements

As a beginner in Typescript, I am delving into creating a typed map structure where the values are associated with specific keys. This can be demonstrated through pseudo JS code without types: const propertyA = "PropertyA"; const propertyB = "PropertyB"; ...

What is the best way to utilize the async pipe along with @defer for efficiently loading and declaring variables in the template within Angular 17

One way I can accomplish this is by using @if. An example of this is: @if(items$ | async; as items), where I can assign the array of items to a variable named 'items' using the 'as' keyword in the template. Is there a similar approach ...

How can I effectively organize an Angular2 component library for optimal efficiency?

Looking to develop an Angular2 datepicker component with the intention of releasing it and using it in multiple projects. Wondering about the best way to structure the project for this specific purpose compared to a typical Angular2 project created with an ...

Ensuring that environment variables are properly set is essential for effective error handling

I am currently integrating my NodeJS and Typescript App to create new config files that utilize .env variables. If a specific variable is not set, I want to trigger an error. After setting up my config file, I encountered some errors; however, I am unsure ...

When you import objects in Typescript, they may be undefined

I have a file called mock_event that serves as a template for creating an event object used in unit testing. Below, you can find the code snippet where this object is initialized: mock_event.ts import {Event} from "../../../models/src/event"; im ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Tips for presenting a row that states "No data found" when the datasource is devoid in Angular using material2

Currently, I am utilizing angular/material2 to showcase a table. <mat-table class="table" #table [dataSource]="dataSource" matSort > <ng-container matColumnDef="{{col}}" *ngFor="let col of displayedColumns"> <mat-header-cel ...

The issue of "Invalid arguments passed to jsPDF.text" encountered while using jsPDF on an nginx server

In my project admin, I have successfully implemented jspdf. The admin panel works perfectly fine on localserver. However, when I deploy it to a live nginx server, the server side throws an error: Error: Uncaught (in promise): Error: Invalid arguments passe ...

Testing a subclass in Angular 6 using Karma and the @Input decorator

After finding no answers to related questions, I've decided to pose my own specific case regarding unit testing an Angular 6 component that is a subclass of a base component. The base component itself includes an @Input decorator and looks like this: ...

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

A guide on dynamically displaying Primeng Components within Angular applications

My task involves dynamically rendering Primeng components along with regular HTML elements. The template for rendering is stored as a string, as shown below: const dynamicTemplate = `<div class="card flex flex-row gap-3 justify-content-cen ...