Cannot read property of type '_id ' of undefined CRUD operations

Viewed 290

I am fairly new to angular and just implementing CRUD operations. I am using a express server which uses mongoose for my back-end and front-end is angular.

My express server is working fine I can do all requests and I can get the list of products to display in my angular application.

When I click on a product or try to delete a product I get the "Cannot read property of type '_id' of undefined"

My question is how can I define the specific product I clicked or deleted using their ID as that is what is needed for the delete request or where am I going wrong here? I dont really understand the undefined error either as I can get all the products and display their id, name brand ect..

I am using _id in my product model and isbn because the id created in postman uses _id which is the one I need in order to delete.

Here's my product service

import { Injectable } from '@angular/core';
import {IProduct} from 'model/product'
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators'

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  private dataUri ='http://localhost:5000/Beauty'

  constructor(private http: HttpClient) { }

  getProducts():Observable<IProduct[]>{

    console.log("get products called"); 

    return this.http.get<IProduct[]>(`${this.dataUri}?limit=10`)
      .pipe(
        catchError(this.handleError
          )
      )
  }

  getProductById(id: string): Observable<any>{
    return this.http.get(`${this.dataUri}/${id}`)
  }

  addProduct(product: IProduct): Observable<IProduct>{
    return this.http.post<IProduct>(this.dataUri, product)
    .pipe(
      catchError(this.handleError)
    )
  }

  updateProduct(id:string, product: IProduct): Observable<IProduct>{
    console.log('subscrbing to update' + id); 
    let productURI: string = this.dataUri + '/' + id; 
    return this.http.put<IProduct>(productURI, product)
    .pipe(
      catchError(this.handleError)
    )
  }

  deleteProduct(_id : string) : Observable<IProduct>{
    let productURI: string = this.dataUri + '/' + (_id); 
    return this.http.delete<IProduct>(productURI)
    .pipe(
      catchError(this.handleError)
    )
  
   }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // Return an observable with a user-facing error message.
    return throwError(
      'Something bad happened; please try again later.');
  }

}


here's the product-crud component

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {IProduct} from 'model/product'
import { Observable } from 'rxjs';
import { ProductService } from '../product.service';

@Component({
  selector: 'app-product-crud',
  templateUrl: './product-crud.component.html',
  styleUrls: ['./product-crud.component.css']
})
export class ProductCrudComponent implements OnInit {

  products: IProduct[];  
  message:string;

  currentproduct: IProduct; 

  constructor(private productservice: ProductService, 
    private router: Router) { }
  ngOnInit(): void {
    this.loadProducts(); 
  }

  clicked(product: IProduct):void{
    this.currentproduct = product; 
    console.log(this.currentproduct._id); 
  }
  loadProducts(){

    this.productservice.getProducts().subscribe({
      next:(value: IProduct[])=> this.products = value, 
      complete: () => console.log('product service finished'), 
      error:(mess) => this.message = mess
    })

  }
  deleteProduct(_id: string, product: IProduct)
  {
    console.log('deleting product'); 

    this.productservice.deleteProduct(product._id)
    .subscribe({
      next:product => this.message = "product is deleted", 
      complete: () => console.log("deleted product"), 
      error: (mess) => this.message = mess
    })
  }
     updateProduct(_id: string){
      this.router.navigate(['update', _id]);
    }

}

and the product-crud component html

<div class="panel panel primary">
    <div class="panel-heading">
        <h2>Product List</h2>
    </div>

    <div class="panel-body">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>
                        Name
                    </th>
                    <th>
                        Category
                    </th>
                    <th>
                        Brand
                    </th>
                    <th>
                        Price
                    </th>
                    <th>
                        id
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let product of products"
                [product] = "p"
                (click) = 'clicked(p)'>
                    <td>{{product.name}}</td>
                    <td>{{product.category}}</td>
                    <td>{{product.brand}}</td>
                    <td>{{product.price}}</td>
                    <td>{{product.isbn}}</td>
                    <td><button (click)="deleteProduct(product.id)" class="btn btn-danger">Delete</button>
                       <button (click)="updateProduct(product.id)" class="btn btn-info" style="margin-left: 10px">Update</button>
                        <button (click)="detailproduct(product.id)" class="btn btn-info" style="margin-left: 10px">Details</button> 
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

1 Answers

Looking at the functions you have in the component, the following changes should make it work.

  1. <tr *ngFor="let product of products" (click) = "clicked(product)"> Here product is a local variable which you need to pass.

  2. Also, the function signature deleteProduct(product.id) and function calls (click)="deleteProduct(product.id)" do not match.

You might want to change these to something like, (click)="deleteProduct(product._id, product)". Similarly check and modify other function calls.

Related