An issue has occurred: Unable to access the 'seatsavailable' property of an undefined object

Currently, I am immersed in a project involving Angular 6 and utilizing the @Input and @Output decorators. In this scenario, I have the Bookride Component functioning as the parent component with RideDetails serving as the child component. Successfully transmitting data from the parent component to the child component using the @Input decorator proved to be smooth sailing. However, my attempts to transfer data from the child component back to the parent component hit a snag, resulting in an error message displayed in the console:

"ERROR TypeError: Cannot read property 'seatsavailable' of undefined"

BookRide Component - HTML(Parent Component)

<tr *ngFor = "let book of shrides | filterpipe:filterargs" (click) = "message = book">
  <td>{{book.startloc}}</td>
  <td>{{book.destination}}</td>
  <td>{{book.seatsavailable}}</td>
  <td (click)="deleteProduct(book.id)"><a>DELETE</a></td>
  <td [routerLink] = "['/update-ride', book.id]" (click) = "update(book.id)"><a>UPDATE</a></td>

<app-ridedetails [cName] = "message" (onRegister)="courseReg($event)"></app-ridedetails>

The above line triggers an error in the console: "ERROR TypeError: Cannot read property 'seatsavailable' of undefined at RestserviceService.push../src/app/restservice.service.ts.RestserviceService.updateRide2 (restservice.service.ts:84)"

BookRide Component - TS

export class RidedetailsComponent implements OnInit { 
seatsavailable: number;
courseReg(seatsavailable: number){
        console.log("Booking ID", seatsavailable);
        this.messages = `Booking Done. Your Booking name is : ${seatsavailable}`;
        this.render = !this.render;
}}

RideDetails Component - HTML(Child Component)

     <tr>
          <td>{{loadData?.id}}</td>
          <td>{{loadData?.name}}</td>
          <td>{{loadData?.car}}</td>
          <td>{{loadData?.seatsavailable}}</td>
          <td>{{loadData?.startloc}}</td>
          <td>{{loadData?.destination}}</td>
      </tr>

<button type="button" (click)="register(loadData.id, loadData.seatsavailable)" [ngClass] = "render ? 'btn-primary' : 'btn-danger'"> {{render == true ? 'Book!' : 'Cancel! Booked ride'}} </button>

RideDetails Component - TS

export class RidedetailsComponent implements OnInit {
  loadData:any;
  sendData: any;
  messages: any;
  render: boolean = true;
  seatsavailable: number;
  ride: Ride[];
  constructor(private restservice : RestserviceService) { }

  ngOnInit() {
  }

  @Input() set cName(sampleObject){
    this.loadData=sampleObject;
  }

  //Child to Parent Communication
  //Sending an event to BookrideComponent and hide the table using @Output Decorator
  @Output() onRegister = new EventEmitter();

  register(bookingID: string, seatsavailable: number, ride: Ride) {
    this.render = !this.render;
    this.onRegister.emit({seatsavailable} as Ride);
    this.messages = `Booking Done(ridedetails). Your Booking id: ${bookingID}`;
    console.log("After clicking on Book button, the seats available data in ride details component is", this.loadData.seatsavailable);
    if(this.loadData.seatsavailable === seatsavailable){
      console.log("this.loadData.seatsavailable", this.loadData.seatsavailable - 1);
      this.restservice.updateRide2(ride, seatsavailable).subscribe( shride => { this.loadData.seatsavailable - 1 });
    } 
   }
}

In analyzing the RideDetails Component, it becomes apparent that the creation of a property named onRegister of type EventEmitter and coupling it with the @Output decorator facilitates the transmission of data from the child to the parent component. Subsequently, within the register() function, the seatsavailable value gets emitted back to the parent component. However, upon reaching the parent component, an error emerges.

A discrepancy also arises in the courseReg() method of the BookRide Component, where the console logs display 'Your Booking name is: [object Object]'.

Answer №1

It appears that everything is correct, but I have a few suggestions for changes in your code. I cannot guarantee that it will work, but you can give it a try.

this.onRegister.emit(seatsavailable);
If you are only sending seatsavailable from the child to the parent, simply pass the value instead of as an object.

When reading your value, use this format:

courseReg(event: any){
        console.log("Booking ID", event.seatsavailable);
        this.messages = `Booking Done. Your Booking name is : ${event.seatsavailable}`;
        this.render = !this.render;
}}

I believe this approach may work, so please give it a try. Thank you and happy coding!

Answer №2

The issue at hand typically arises from the object not being resolved prior to the route loading. To mitigate this, we employ the existential/safe operator book? (which checks its 'existence'). If this error stems from that source, the recommended solution (unless a loading spinner is in use) is to implement an Angular resolver. This resolver will ensure that the data in your component is resolved before the route loads.

If you are unfamiliar with Resolvers, I highly recommend reading this informative article: https://codeburst.io/understanding-resolvers-in-angular-736e9db71267

By doing so, your data will be accessible in the component prior to the route being resolved, eliminating the need to check for data existence using ?.

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

Issue with Angular 2: Service not reflecting updated variable

I am currently working on creating an API service and trying to assign the data to a variable. However, I am facing an issue where the variable is not updating and ends up being undefined when I try to log it after calling the API service. import {Compone ...

Incorporating Swagger-UI into an Angular 10 project

Looking to integrate Swagger UI into your Angular application? After researching extensively, I found that the recommended approach is now to use the swagger-ui package instead of swagger-ui-dist for single-page applications. For those using React, there ...

404 error received from Angular 2 API call despite successful testing of service

I've been attempting to make a web service call from my Angular 2 application. private baseUrl: string = 'http://localhost:3000/api'; getPatterns(): Observable<Pattern[]> { const patterns$ = this.http .get(`${this.baseUrl ...

Generate a fresh array by filtering objects based on their unique IDs using Angular/Typescript

Hey there, I am receiving responses from 2 different API calls. Initially, I make a call to the first API and get the following response: The first response retrieved from the initial API call is as follows: dataName = [ { "id": "1", ...

What is the purpose of the @NgModule annotation in Angular Material?

I've been struggling with using Angular-Material Components in different components. Despite watching and reading various tutorials, I still can't seem to get them to work. The error message I keep encountering is: compiler.js:2430 Uncaught Erro ...

Is it possible to customize the design of Angular Material Tabs on a per-page basis?

Currently working on customizing the appearance of a specific mat-tab, I've come to learn that using :ng-deep makes the style apply globally, Is there any method to modify the style only for this particular component? Appreciate any insights or sug ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...

There is only a singular font awesome icon that appears properly based on the conditions set by [ngClass

I'm currently developing a user profile feature that allows users to submit links to their social media accounts. Each account is represented by a clickable icon, and the selection of which icon to display is based on various conditions within [ngClas ...

Sanity.io and using images with next/image extension glitch

Hello everyone, I'm excited to join Stack Overflow for the first time. Currently, I am working on a project using Next.js with Sanity as my headless CMS. I have come across what appears to be a TypeScript type issue. Here is the link to the code on Gi ...

The production build encountered an issue as it was anticipating 3 arguments, however, it only received

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'elipsis' }) export class ElipsisPipe implements PipeTransform { transform(text, length, clamp) { text = text || ''; clamp = clamp || '...& ...

Tips for efficiently handling state across various forms in separate components using only one save button within a React-Redux application

I am currently developing an application that combines a .NET Core backend with a React frontend, using React Hook Form for managing forms. Unlike typical single-page applications, my frontend is not built in such a way. On a specific page of the applicat ...

Exploring Angular 4.0: How to Loop through Numerous Input Fields

I am looking to loop through several input fields that are defined in two different ways: <input placeholder="Name" name="name" value="x.y"> <input placeholder="Description" name="description" value"x.z"> <!-- And more fields --> or lik ...

Dynamic autocomplete in Oclif utilizing an HTTP request

Is it feasible for Oclif to support the functionality of making API calls to retrieve values for autocomplete? Consider this scenario: A database stores multiple users information Upon typing show users <Tab> <Tab>, the CLI triggers an API ca ...

Incorrect deduction of the argument type for a higher-order function

If I wanted to create a function that takes an object of type T and another value, where the type P should somehow be restricted by T (for example, P should be an array of keys of T), I could easily write it like this: function customFunction<T, P exte ...

Adding an item to an array in Angular 2 using JavaScript!

In my Angular2 form, I have a field that consists of an array of objects. I've successfully created a table with a Delete Row button for each row and an Add Row button using the push() and slice() methods in JavaScript. However, there's a major ...

The Ionic and Angular application solely displays dynamic HTML with no encapsulation using ViewEncapsulation.None

I'm struggling to grasp the concept of encapsulation: ViewEncapsulation.None within the @Component. @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], encapsulation: ...

Updating the legend boxes of a chart in Chart Js to match the style of the graph lines

I need assistance updating the legend boxes of my graphs with graph line style. https://i.sstatic.net/zhi4L.pngActual Consumption https://i.sstatic.net/dAjlp.png Average Use https://i.sstatic.net/YMC7I.png Here is the code snippet I am currently using, ...

The Angular Material Table experienced a collapse when trying to render over 20 columns simultaneously

Currently, I am experiencing an issue in Angular Version 5 where the Angular Material Table collapses when rendering more than 20 columns. Here is a snapshot of what my table looks like: https://i.stack.imgur.com/MXfvQ.png https://i.stack.imgur.com/XHWgq ...