Erase Mistake in Pop-up Angular JSON Information and Bootstrap

Encountering an ERROR TypeError:

Cannot read property 'id' of undefined
while attempting to delete data in a modal using Bootstrap. When I click the button, I correctly receive the data in JSON format in the modal (as shown in the image). Any ideas on how to resolve this issue?... By the way, the insert, select, and update functionalities work as intended, but the delete operation is throwing this error.

component.ts

selectedExamen;
examenes: Examen[];
@ViewChild('btnClose') btnClose: ElementRef;
constructor(private dataService: dataService, public dialog: MatDialog) {
  this.getExamenes();
  this.selectedExamen = {
    id: -1, nombreExa: '', descripcionExa: '',
    release_date: '', fechaExa: '', categoriaExa: '', nombrePac: '',
    apellidoPac: '', rutPac: '', apellidoDoc: '', nombreDoc: ''
  };
}
delete (exa): void {
  this.dataService.deleteExamenes(exa.id);
  this.examenes = this.examenes.filter(e => e !== exa);
}
examenClicked = (exa) => {

  this.dataService.getOneExamen(exa.id).subscribe(
    (data: Examen) => {
      this.selectedExamen = data;
      console.log('JSON DATA --->', data);
    },
    error => {
      alert('Error al Conectar Datos ');
    }
  );
}

component.html

<button class="btn btn-danger" href="#deleteCategory" (click)="examenClicked(categorias)" data-toggle="modal" >Borrar</button>
<button class="btn btn-secondary" type="button" href="#signinModal" data-toggle="modal"  (click)="examenClicked(categorias)">Editar</button>  

"modal button"
 <button type="button" class="btn btn-danger" (click)="delete()">Borrar</button>

service (I suspect the mistake lies here?)

deleteCategorias(id: number): Promise <void> {
  const url = `${"http://127.0.0.1:8000/categoria"}/${id}`;
  return this.http.delete(url, { headers: this.headers })
    .toPromise()
    .then(() => null)
}
getOneCategory(id): Observable <Categoria> {
  return this.httpClient.get<Categoria>(this.baseurl + '/categoria/' + id ,
  ).pipe()
}

The error occurs when I press the button in the modalhttps://i.sstatic.net/8ApKM.png

Answer №1

The onClick event for your modal button is currently being handled by the delete(exa) event handler. This event handler expects an argument of "exa", but you are invoking it with just delete():

<button type="button" class="btn btn-danger" (click)="delete()">Delete</button>

To resolve this error, you need to modify your component's delete() method to not require an exa parameter:

selectedExamen;
examenes: Examen[];
@ViewChild('btnClose') btnClose: ElementRef;
constructor(private dataService: DataService, public dialog: MatDialog) { }

ngOnInit(){ //Initialization code should be placed inside ngOnInit() whenever possible
   this.getExamenes(); //What is the purpose of this method???
}

delete (): void { //Removed exa parameter
  if(this.selectedExamen != undefined){ //Utilize selectedExamen which you retrieve upon opening the modal.
     this.dataService.deleteExamenes(this.selectedExamen.id).subscribe(
         (deleteSuccess) => {
             alert('Delete successful');
         },
         (error) => {
             alert('Error deleting');
         }
     )
     this.examenes = this.examenes.filter(e => e !== this.selectedExamen);
  }else{
     alert('No examen selected');
  }
}


examenClicked(exa){ //examenClicked = () => {} is equivalent to examenClicked(){}
  this.dataService.getOneExamen(exa.id).subscribe(
    (data: Examen) => {
      this.selectedExamen = data;
      console.log('JSON DATA --->', data);
    },
    error => {
      alert('Error connecting to data');
      this.selectedExamen = { //Moved this from the constructor to here
         id: -1, nombreExa: '', descripcionExa: '',
         release_date: '', fechaExa: '', categoriaExa: '', nombrePac: '',
         apellidoPac: '', rutPac: '', apellidoDoc: '', nombreDoc: ''
       };
    }
  );
}

In addition, ensure that your service is using the same HttpClient service instance as your getOneCategory method:

deleteCategorias(id: number): Promise <void> {
  const url = `${"http://127.0.0.1:8000/categoria"}/${id}`;
  return this.httpClient.delete(url, { headers: this.headers });
  //It's preferable to use Observables instead of promises for making HTTP requests.
  //You are using .subscribe() in `delete()` to send the HTTP request.
}


getOneCategory(id): Observable <Categoria> {
  return this.httpClient.get<Categoria>(this.baseurl + '/categoria/' + id);
}

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

item uploaded via internet not restricted

Recently delving into Angular2, I am currently engrossed in constructing a basic application that showcases a list of objects. My goal is to click on one object and delve into a detailed view of it. However, while attempting to access the properties of the ...

Clear all events from an HTML element and its descendants with TypeScript

Each time the page loads, I have HTML from an API that is constantly changing. Is there a way to strip away all events attached to it? The original HTML looks like this: <div id="content"> <h2 onclick="alert('hi');">Test 1< ...

Leverage the event handler within a React Component when working with TSX tags

Is there a way to expose an event handler that is defined within a React Component in an HTML-like tag? For example: <MyComp param1="abc" param2="def" onDoSomething={this.someMethod} /> I am trying to define the onDoSomething event, but currently I ...

Tips for injecting a service into a class (not a component)

Can you inject a service into a class that is not a component? Consider the following scenario: Myservice import {Injectable} from '@angular/core'; @Injectable() export class myService { dosomething() { // implementation } } MyClass im ...

Encountered an error while attempting to execute Angular application due to schema validation failure

Encountering errors in my Angular 7 Application on the development server. After running ng serve, below is the error that surfaced: D:\suman\ftoss\New TFS\FtossAngularWeb\Pre11WebV1>ng lint -fix Your global Angular CLI ...

I am looking to incorporate serial numbers into two distinct loops within an Angular application

I need help adding a serial number using two separate ngFor loops. Here is the code: <table> <tr> <th>Sr</th> <th>Name</th> </tr> <ng-container #atvalue> <tr *ngFor="let item of items; l ...

Creating an uncomplicated search bar that dynamically adjusts values based on its function

Summing it up, there is a div situated within my app.component.html: <div class="col-lg-6 search-div"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for..."> <span class="input-group-b ...

Is there a way to navigate to a separate homepage based on the user's login status in Angular?

My goal is to automatically redirect users to the /dashboard page once they are logged in. The default landing page is set to /home, but for logged in users, it should be redirected to /dashboard. In my user service class, I have created a sharedUser usin ...

Issues with Angular 2 template not refreshing during testing

I'm struggling to get this to function properly. it('should have the expected <h1> text', async(() => { let fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const sectionEl = fixture.debugElement.que ...

Issue with alignment of Bootstrap 4 dropdown menu within grid layout

I seem to be encountering an issue with my code, as part of the dropdown menu is appearing off-screen. Can you help me identify what I'm doing wrong? Interestingly, when scrolling horizontally, the menu position corrects itself. <div class="contai ...

The error message "pipe does not exist on type" is encountered when attempting to use pipes with RxJS 6

I am in the process of upgrading my Angular 4 to Angular 6 application, which includes several RxJS operators. I attempted to pipe them together but encountered issues with the syntax. The problem arises specifically on the fifth pipe. Can someone please a ...

The reactivity of arrays in Vue components' props is limited

I've got an array with component data that I'm attempting to render using v-for <div :style="style" class="editor-component" v-for="(component, index) in components"> <Component :is="component.name" v-bind="component.o ...

Customize styles for a specific React component in a Typescript project using MaterialUI and JSS

I'm currently exploring how to customize the CSS, formatting, and theme for a specific React component in a Typescript/React/MaterialUI/JSS project. The code snippet below is an example of what I've tried so far, but it seems like the {classes.gr ...

Prevent data loss on webpage refresh by using Angular's local storage feature

As a beginner in Angular, I am exploring ways to retain user input and interactions on my webpage even after a refresh. After some research, I came across using local storage as a viable solution. A different answer suggested utilizing the following code s ...

Boost Page Speed with Angular

Currently, I am working on a project using Angular and encountered an issue with testing the page speed on GTmetrix. Despite generating the build with the command ng build --prod--aot, the file size is 1.9mb, leading to a low speed in GTmetrix's analy ...

Modifying content directly within the Angular Material data table

Can you create an Angular Material data table with inline editing capability? Specifically, is it possible to have cells in certain columns be editable as soon as the table loads (similar to the Editable Email column fields shown in the image below)? If th ...

How to activate a directive in Angular2 using a component when clicking

Currently, I have implemented a directive that adds a box shadow to any element hovered on the page. However, I need this functionality to start only after clicking a button. The issue I am facing is that it only applies to a single element at a time. Cli ...

utilize the getStaticProps function within the specified component

I recently started a project using Next.js and TypeScript. I have a main component that is called in the index.js page, where I use the getStaticProps function. However, when I log the prop object returned by getStaticProps in my main component, it shows a ...

Improving performance with Bootstrap 4 Inline Grid or utilizing Sass mixins

When I initially delved into the realm of Bootstrap, my approach to setting up grids was mostly inline using classes. For some reason, I found it more visually appealing and easier to comprehend. However, as time passed, I have transitioned to utilizing s ...

Angular: Concealing a Component within a Controller

Being new to Angular, I am trying to figure out how to programmatically hide/show a component using the controller. I am having trouble understanding how to access my component and set ng-hide to false. Currently, my controller includes a service call. Af ...