What could be causing the error in my Angular code that reads "cannot read property of undefined"?

I am working with a web API to retrieve data in JSON format. The data is returned successfully, but when I try to loop over it, I encounter an error stating 'Cannot read the property of undefined CustomerName'.

    [System.Web.Http.HttpGet]
    public object GetBookings(string SearchByParam = "", byte WhichRecords 
      = 1)
    {
        List<ZahidCarWash.ViewModels.BookingArrivalCancellationViewModel> 
        lstBookingArrivalCancellation = 
      BookingsRepository.SelectCustomerBookingDetailsAndroid(SearchByParam, 
      WhichRecords);

        if (lstBookingArrivalCancellation.Count > 0)
        {
            return Json(new { ReturnStatusJSON = true, lstArrivalCancellation = lstBookingArrivalCancellation });
        }

        else
        {
            return Json(new { ReturnStatusJSON = false, lstArrivalCancellation = lstBookingArrivalCancellation });
        }
           }

Customer.service.ts

export class CustomerService {
    formData: Customer;
    Data: Customer[];

    constructor(private http: HttpClient) { }

    getData() {
        return
        this.http.get('http://localhost:13924/api/AndroidOperations/GetBookings')
            .subscribe(function(data: any) {
            this.Data = data['lstArrivalCancellation'] as Customer[];
            console.log(this.Data);
        });
    }

}

customer-list.component.ts

export class CustomersListComponent implements OnInit {

    constructor(public service: CustomerService) {
    }

    ngOnInit() {
        this.service.getData();
    }

}

.html

 <table class="table table-hover">
  <tr *ngFor="let d of service.Data | async"></tr>
   <td *ngIf="CustomerName">{{d.CustomerName}}</td>
   <td>Tr</td>
 </table>

Customer Mode:

   export class Customer {
     CustomerID: number ;
     CustomerName: string;
     ContactNo: string;
     VehicleRegNo: string;
     fk_VehicleMakeID: number;
     VehicleModel: number;

    }

Answer №1

Consider updating the ngIf directive in your HTML code like this:

<td *ngIf="CustomerName">{{d.CustomerName}}</td>

to

<td *ngIf="d">{{d?.CustomerName}}</td>

Answer №2

Instead of checking for CustomerName in your *ngIf statement, make sure to check for d.CustomerName. Remember, 'd' is always present since you are iterating through the collection it belongs to. If d.CustomerName is undefined, it will cause an error.

<div *ngIf="d.CustomerName">{{d.CustomerName}}</div

This adjustment should solve the issue.

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

Looking for a type that combines multiple options

I am interested in incorporating union types as function arguments, with the ability to utilize the arguments and have any missing ones default to undefined. However, when it comes to 'name' and 'age', there seems to be a type conflict ...

Is there a way to keep chart values from disappearing on the edges of the x-axis in Highcharts when zooming in?

Currently, I am working with highcharts-react-official to create a histogram using typescript. However, I have encountered an issue where the values on the edges of the x-axis disappear when users zoom in (highlighting relevant x-axis values). View Example ...

Exploring the extraction of anchor tags in asp.net

Is using regex the most effective method for capturing and analyzing all anchor tags when parsing a block of HTML in plain text format, or does the .NET library offer better functionality? ...

Guide to making an array of objects reactively with formControlName

I am currently working with an Angular application. Within this application, I have a reactive form that is declared as form!: FormGroup<GlobalBean> Within the GlobalBean interface, there is an array of another bean defined as: export interface Glo ...

"Using rxjs, a value is delivered within the subscribe function

function createSingleMapService(mapServiceFactory) { return mapServiceFactory.switchSingleMapService().subscribe((service)=>{ return service }) } This snippet is a factory function in Angular that creates a single map service. The 's ...

Creating an ESNext JavaScript file and integrating it into an Angular 2 project: A comprehensive guide

I am facing an issue with my js file named UserService.js and source.js, which has been transformed using transformer typescript. My objective is to integrate this transformed js file into Angular. UserService.js import { Source } from "./source" ...

The ASP.Net button fails to trigger the Post method

I need help with passing data from my view to the Details method, which then sends the values to a mail method. Within my view, there is a form where users can submit comments. Upon clicking the send button, the value in the form should be sent to the Det ...

Determining a value that increases to yield a fresh sum

I'm currently developing a character generator that determines your score based on the experience points you allocate to it. The scoring system is such that 1 XP gives you a score of 1, 3 XP gives you a score of 2, 6 XP gives you a score of 3, 10 XP g ...

How can I configure Angular to redirect to an error page whenever an error is encountered in an HTTP API request?

With over 50 HTTP APIs in my application, I'm looking for a way to automatically route to a specific page whenever an error message or issue arises with one of the APIs. Instead of manually adding routing to each service, I want to find a simpler and ...

Is it possible to transfer parameters from one page to another page using the pop method in Ionic 2?

Is it possible to pass parameters from one page to another during a push operation, but how can this be done during a pop operation? showfilter(){ this.navCtrl.push(FilterPage,{ fulldetail : this.selectedarea }); } Can you explain how ...

A single image path utilized for both development and production stages during the Angular build process

I am struggling to determine the correct path for my images to work seamlessly on both development and production environments. Currently, I can only get them to display properly on my local development server. However, when I use the command ng build --pr ...

Force Angular to log the user out abruptly

I am currently utilizing .Net Core Web API on the backend and Angular on the frontend for my project. When a user signs in, I generate a JWT token for authentication purposes. However, I have chosen not to store this token in the database. One issue I&a ...

Tips for ensuring a required json key is present while still allowing the value to be null

In my API, I have a model that includes a nullable double. I am looking to enforce the requirement for anyone posting to include the key in the JSON body. Currently, I am utilizing [FromBody] to retrieve the data from the JSON in the post function. Do you ...

Is there a way to restrict the number of line breaks in a multiline asp:TextBox control?

Is it possible to restrict a multiline asp:TextBox to only display content on 3 lines using either javascript or C#? ...

The Formik and React error is indicating that the '{ refetch: any; }' type is absent

When attempting to pass a prop down to my EmailSignupScreen, I encountered an error message. This issue arose while experimenting with Formik and Typescript. "message": "Type '{ refetch: any; }' is missing the following properties from type &apo ...

ASP.NET Development: Understanding Architectural Design and Class Diagrams

Looking to dive into ASP.NET Development. Does anyone have any recommendations for a resource that provides sample code, architecture, class and sequence diagrams for a simple ASP.NET application with 3 / 4 / n-tier structure? Any help would be greatly a ...

Refresh grid components with checkbox feature - ionic 2

I'm in need of assistance. I have a grid with multiple columns and I want to update the selected rows in my database by clicking a button. Unfortunately, I haven't been able to find any information on how to do this. Below is the code I am curre ...

Securely insert code into a MySQL database using C# (ASP.NET)

Seeking a secure method to insert code into my MySQL database using C# and ASP.NET. Open to any recommendations. I have done some research on Google but mostly found PHP examples. Appreciate your help. ...

Hand over the component method as an argument to a class

One of my components, called First, is responsible for creating a new instance of a Worker class. During the creation process of this class, I intend to pass the Read method as a callback method. Once this class completes its task, it will then invoke thi ...

Is Node.js and Express.js necessary when utilizing Angular2 in development?

A web application prototype was developed using the following technologies: Angular 2 TypeScript ASP.Net WebAPI 2 Mongo DB Karma/Jasmine Node.js (solely as a server, in accordance with Angular2 Quick Start instructions) Given the tech stack mentioned ab ...