Unable to access the property 'filter' of undefined. I only want to extract the client with the specific client_id from the clients array

I have written some TypeScript code for a function that checks the client_id in my application.

public clients: Client[];
  ngOnInit() {
    this.cs.getAllClients().subscribe(
      clients => {
        this.clients = clients;
        console.log(clients)
      }
    );}
      getName(clientid: string) {
        const [filteredClient] = this.clients.filter(pt => pt.client_id === clientid);
         if (typeof filteredClient !== 'undefined' && clientid === filteredClient.client_id) {
          console.log(filteredClient.clientName)
          return filteredClient.clientName;
        }
      }

This function is used in the HTML code as well,

 <table class="bordered table-bordered" [mfData]=" sale | dataFilter : filterQuery" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage"
    [(mfSortBy)]="sortBy" [(mfSortOrder)]="sortOrder">
    <thead style="color:black; background:rgb(207, 235, 245);border:1px solid rgb(190, 190, 190);">
      <tr>
          <th>
              <mfDefaultSorter by="client_name">Name</mfDefaultSorter>
            </th>
        <th>
          <mfDefaultSorter by="sale_date">Data</mfDefaultSorter>
        </th>
       </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of mf.data">
        <td>{{getName(item.clientName)}}</td>
        <td>{{item.sale_date | date:'d/MM/yyyy'}}</td>
      </tr>
    </tbody>
  </table>

However, when I try to display the client name, it doesn't show up and I get an error in the console saying 'Cannot read property 'filter' of undefined.'

Could someone please help me identify the issue with this code?

Thank you in advance!

Answer №1

getAllClients is an observable and therefore asynchronous. The view may load before the data is received in the subscribe callback.

To solve this issue, you have a couple of options:

First, initialize an empty array to avoid having an undefined array.

public clients: Client[]=[];

Another option is to use *ngIf in your template.

<table *ngIf="clients" class="bordered table-bordered" [mfData]=" sale | dataFilter : filterQuery" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage"

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

Uploading Code to Github for the Second Round

After successfully building my Angular code and publishing it to the Github repository, I specified the directory as dist/projectname. As a result, only my dist folder is visible on the Github Pages in my repository. Now, I want to push the complete code ...

Working with multidimensional arrays in AngularJS using ng-repeat

I have noticed that there are numerous inquiries on this subject that have already been resolved. As someone who is new to Angular, I am struggling to grasp the concept of how the {{variable}} notation actually functions. When using an API, the response ...

Issue with Angular5: Spinner malfunctioning during initialization of the page

My service emits two events dataLoaded and loadingData. I want to display a GIF image when data is loading and hide it when data is loaded. In the component, I handle both events and update a Boolean variable accordingly. However, on the initial page load, ...

What is the best way to convert an Express route to Typescript?

I'm trying to create a wrapper called loginRequired for my Express route, but I'm struggling to define the right types. This is what my loginRequired wrapper looks like: export const loginRequired = (fn) => (req, res, next) => { // Ch ...

How to add icons to HTML select options using Angular

Looking for a way to enhance my component that displays a list of accounts with not only the account number, but also the currency represented by an icon or image of a country flag. Here is my current component setup: <select name="drpAccounts" class= ...

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

`Why am I unable to achieve the proper body shape with Angular?`

When using Angular to retrieve registration information from an HTML form and then posting it to an API path, everything seems to be working fine. However, the word "work" is being printed and I am unable to get the value in the body. I have tested the POS ...

Tips for modifying the data type of a property when it is retrieved from a function

Currently, I have a function called useGetAuthorizationWrapper() that returns data in the format of { data: unknown }. However, I actually need this data to be returned as an array. Due to the unknown type of the data, when I try to use data.length, I enc ...

Angular2: Number types being converted to strings by the + operator

Why is the '+' operator in my binding treating variables as strings instead of numbers, unlike other arithmetic operators like -, * and / which correctly perform arithmetic operations on them as numbers, as expected based on their types in the as ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

The element being bound, 'something here', is assumed to have a type of 'any'

Hey everyone, I'm just starting out with React and I was attempting to create a modal popup after clicking a button. However, I encountered this error: "Binding element 'children'/active/setActive' implicitly has an 'any' type ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

What distinguishes ES6 from ES2015 in the TypeScript compiler option `--libs`?

Can you explain the distinction between ES6 and ES2015 in the TypeScript compiler option here? Also, what does --libs do? https://i.sstatic.net/iUv8t.png ...

The combination of Material UI and React Hook Form is encountering an issue with submitting disabled checkboxes

My current challenge involves ensuring that all fields are disabled while the form is submitting. I have successfully implemented this for text, selects, and radios, but I am facing difficulties with required checkboxes. I am working with nextjs typescrip ...

What are the steps to enable full functionality of the strict option in TypeScript?

Despite enforcing strict options, TypeScript is not flagging the absence of defined types for port, req, and res in this code snippet. I am using Vscode and wondering how to fully enforce type checking. import express from 'express'; const app ...

Determining function return property type in Typescript by mapping interface argument property

In order to manage messaging between the browser and a web worker, I have developed a generic class. Each side creates a class that can send specific messages and acknowledge them on the other side with a returned result in a payload. The implementation is ...

Issue with Cors error while sending post requests from Chrome to DotNet Core 2.1 Api secured with Jwt and [Authorize] in Angular 8

Dealing with CORS is a common problem that I have faced in the past. Enabling CORS in DotNet Core Api startup.cs has always worked for me, but this time the issue seems a bit more peculiar. In my Angular 8 app, the post request made during login (without ...

Tips for personalizing Ion text area in Ionic?

Seeking assistance on how to effectively utilize ion-textarea. As a novice in the realm of Ionic, I am encountering various challenges while working with this feature. The issue lies in the fact that instead of displaying a scrollbar on the right side, the ...

Is it possible to dynamically create an interface using an enum in TypeScript through programmatically means?

Recently, I defined an enum as shown below: enum EventType { JOB, JOB_EXECUTION, JOB_GROUP } Now, I am in need of creating an interface structure like this: interface EventConfigurations { JOB: { Enabled?: boolean; }; JOB_EXECUTION: { ...

Provide an instance of mockClient for AWS SQSClient in a TypeScript class

I'm currently working on unit testing a piece of code that relies on a constructor with an SQSClient object for interacting with an sqs queue. To write effective unit tests, I need to mock the client so that I can test the code without actually access ...