使用Realtime Database选中商品时如何展示对应商品详情?
问题修复方案
根因说明
- 类型定义错误:获取单个商品详情的返回值被错误声明为数组类型,实际应为单个商品对象
- 数据请求逻辑与数据库结构不匹配:当前请求路径直接取
productos/${id},但从返回整个分类商品的现象判断,Firebase数据库中productos节点下第一层级是分类ID,分类ID下才是对应的商品ID,要么是请求路径缺少分类层级,要么是路由传递的参数实际为分类ID而非商品ID。
修复步骤
1. 修正ProductosService中的getProducto方法
先把错误的数组返回类型改成单个商品对象类型,如果你的数据库确实是分类下挂载商品,需要同时传入分类ID和商品ID查询:
// 常规单参数方案(适配productos下直接存商品ID的结构) getProducto(id:string) { return this.http.get<ProductoDescripcion>(`https://angular-html-2b54e-default-rtdb.firebaseio.com/productos/${id}.json`) } // 适配分类嵌套结构的双参数方案(按需选用) getProducto(categoriaId:string, productoId:string) { return this.http.get<ProductoDescripcion>(`https://angular-html-2b54e-default-rtdb.firebaseio.com/productos/${categoriaId}/${productoId}.json`) }
2. 修正ComprarComponent中的变量类型和逻辑
把原来声明为数组的producto改为单个对象类型,调整赋值逻辑:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ProductosService } from '../../services/productos.service'; import { ProductoDescripcion } from '../../interfaces/producto-descripcion.interface'; @Component({ selector: 'app-comprar', templateUrl: './comprar.component.html', styleUrls: ['./comprar.component.css'] }) export class ComprarComponent implements OnInit { cargando = true; // 修正为单个商品对象类型 producto?: ProductoDescripcion; id:string; constructor( private route: ActivatedRoute, public ProductoService:ProductosService) { } ngOnInit(): void { this.route.params .subscribe(parametros => { this.id = parametros['id'] // 如果用双参数方案此处补充传入分类ID即可 this.ProductoService.getProducto(this.id) .subscribe( (producto: ProductoDescripcion) => { this.producto = producto; console.log(producto) this.cargando = false; }); }); } }
3. 核对路由配置
检查商品列表跳转详情的传参逻辑,确认传递的参数是商品ID而非分类ID,如使用双参数方案需要在路由中新增分类ID参数传递。
内容的提问来源于stack exchange,提问作者Manuel Enrique
相关产品推荐
相关产品推荐

