无法读取未定义 CRUD 操作的“_id”类型的 属性

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

我对 angular 还很陌生,只是实施 CRUD 操作。我正在使用一个快速服务器,它在我的后端和前端使用猫鼬 angular。

我的快递服务器运行良好,我可以处理所有请求,并且可以获取要在我的 angular 应用程序中显示的产品列表。

当我点击一个产品或尝试删除一个产品时,我收到“无法读取 属性 类型 '_id' 未定义的

我的问题是如何使用他们的 ID 来定义我点击或删除的特定产品,因为这是删除请求所需要的,或者我哪里出错了?我也不太理解未定义的错误,因为我可以获得所有产品并显示它们的 ID、名牌等..

我在我的产品模型和 isbn 中使用了 _id,因为在 postman 中创建的 id 使用了 _id,这是我需要删除的 id。

这是我的产品服务

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.');
  }

}


这是 product-crud 组件

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]);
    }

}

和 product-crud 组件 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. <tr *ngFor="let product of products" (click) = "clicked(product)"> 这里的 product 是一个你需要传递的局部变量。

  2. 此外,函数签名 deleteProduct(product.id) 和函数调用 (click)="deleteProduct(product.id)" 不匹配。

您可能希望将这些更改为 (click)="deleteProduct(product._id, product)" 之类的内容。同样检查和修改其他函数调用。