javascript - 问题获取 ID( Angular Material - Firestore)

标签 javascript angular firebase google-cloud-firestore angular-material

我在 Angular Material 中实现表单时遇到问题,delProduct() 函数不起作用,editProduct() 函数也不起作用。

getProducts()函数获取完整的数组(包括ID),

将完整元素的控制台日志添加到 delProduct() 函数得到完整的数组,但没有 id。

代码列表-products.components.ts

export class ListProductsComponent implements OnInit {
  
  productos: any[] = [];
  dataSource: MatTableDataSource<any>;
  displayedColumns: any[] = [
    'cantidad',
    'nombre',
    'ubicacion', 
    'categoria',
    'subcategoria',
    'moneda',
    'precio',
    'action'
  ];
  @ViewChild(MatPaginator)
  paginator!: MatPaginator;
  @ViewChild(MatSort)
  sort: MatSort = new MatSort;

  constructor(private _ProductService: ProductService,
              private afs: AngularFirestore) {
    this.dataSource = new MatTableDataSource(this.productos);
  }

  ngOnInit(): void {
    this.getProducts();
  }

  ngAfterViewInit() {
    this.afs.collection('productos', ref=> ref.orderBy('fechaCreacion', 'desc')).valueChanges().subscribe(data => {
      this.dataSource = new MatTableDataSource(data);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    })
  }

  getProducts() {
    this._ProductService.getProducts().subscribe(data => {
      this.productos = [];
        data.forEach((element:any) => {
      this.productos.push({
        id: element.payload.doc.id,
        ...element.payload.doc.data()
      })
      })
      console.log(this.productos);
    });
  }


  delProduct(element: any, index: any) {
   // const data = this.dataSource.data;
   //   data.splice((this.paginator.pageIndex * this.paginator.pageSize) + index, 1);
   //   this.dataSource.data = data;
   //   this._ProductService.delProduct(element.id)
    console.log('ID', element.id)
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
}

代码list-products.component.html(项目显示正常,只有我编辑/删除功能有问题)

 <ng-container matColumnDef="action">
        <th mat-header-cell *matHeaderCellDef> Action </th>
        <td mat-cell *matCellDef="let element; let i = index">
          <mat-icon [routerLink]="['/edit-product/', element.id]">edit</mat-icon>
          <mat-icon (click)="delProduct(element, i)">delete</mat-icon>
        </td>
      </ng-container>

代码 product.service.ts

export class ProductService {

  constructor(private firestore: AngularFirestore){ }
   
    getProducts(): Observable<any>{
     return this.firestore.collection('productos', ref=> ref.orderBy('fechaCreacion', 'desc')).snapshotChanges();
   }
    delProduct(id: string): Promise<any>{
     return this.firestore.collection('productos').doc(id).delete();
   }
    editProduct(id: string, data:Product): Promise<any>{
     return this.firestore.collection('productos').doc(id).update(data);
   }
}

最佳答案

您正在读取数据两次。一次有 id(使用 snapshotChanges),一次没有 id(使用 valueChanges)。

我建议直接在每个文档中放置一个 id 字段。它让一切变得更简单。

关于javascript - 问题获取 ID( Angular Material - Firestore),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66733310/

相关文章:

javascript - 将多个复选框值存储在变量或数组中

angular - 2 个组件之间的 2 路绑定(bind)仅适用于第一个字母

ios - swift 火力地堡 : how to check user is verified after send email?

javascript - 处理 HTTP 请求失败

javascript - Angular 5:渲染列表时出现 Observables 错误

firebase - recyclerview 的 onBindViewHolder 中的 Android Firebase 监听器

android - Firebase 云消息传递 : best practice

javascript - 在单击标签滚动期间需要修复表格

javascript - 在 jQuery 中向上遍历 DOM 以获取父元素

javascript - jquery datepicker 根据两个日期之间的差异更改输入值