![](/img/trans.png)
[英]How to get ID of collection in Firestore with angular Firestore
[英]Problem get ID (Angular Material - Firestore)
我在 Angular 材料中实现表单时遇到问题, delProduct()
function 不起作用,editProduct editProduct()
) function 也不起作用。
getProducts()
function 得到完整的数组(包括ID),
将完整元素的控制台日志添加到delProduct()
function 会得到完整的数组,但没有 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();
}
}
}
代码列表-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);
}
}
您正在读取数据两次。 一次有 ids(使用 snapshotChanges),一次没有 ids(使用 valueChanges)。
我建议在每个文档中直接放置一个 id 字段。 它使一切变得更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.