我有一個名為“crear-pedido”的 Angular 組件,它顯示了一個專案串列(讓一行產品),我希望用戶能夠單擊 ID 列值并將應用程式路由到一個名為“detalle-productos”的子組件”。本質上:產品串列,如果您單擊 product.ID,則會顯示一張卡片,其中顯示產品的詳細資訊。
相關路由配置:
const routes: Routes = [
{ path: 'crear-pedido', component: CrearPedidoComponent,
children: [
{path: ':ID', component: DetalleProductosComponent},
]},
];
我將 row.ID 資料傳遞給子組件,如下所示:
<td mat-cell *matCellDef="let row"><a [routerLink]="['/crear-pedido', row.ID]"> {{row.ID}} </a> </td>
這是“detelle-productos.component.ts”檔案:
import { Component, OnInit } from '@angular/core';
import { Producto_interface } from '../producto_interface';
import product_list from '../product_json.json'
import { ActivatedRoute } from '@angular/router';
import { Observable, switchMap } from 'rxjs';
@Component({
selector: 'app-detalle-productos',
templateUrl: './detalle-productos.component.html',
styleUrls: ['./detalle-productos.component.css']
})
export class DetalleProductosComponent implements OnInit {
productos: Producto_interface [] = product_list;
selectedProduct: Observable<Producto_interface>;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.selectedProduct = this.route.paramMap.pipe(
switchMap(params => {
const id = params.get('ID');
console.log("Inside oninit")
console.log(this.productos.filter(p => p.ID.toString() == id?.toString()))
return this.productos.filter(p => p.ID.toString() == id?.toString())
})
)
}
}
如您所見,組件將包含所有產品的 JSON 檔案放入“product_list”,ngOnInit() 方法接收路由值并過濾 product_list 以找到正確的產品。目標是將產品資訊傳遞給 selectedProduct,然后在 HTML 中顯示。
回傳之前的 console.log 作業正常:
0: Object { ID: "606", Nombre: "Tapitas Gran Valle Galleta Blanca 9 KG", Linea: "Tapitas", … }
這是相關的HTML:
<mat-card class="product-card" *ngIf="selectedProduct | async as Producto_interface">
<mat-card-subtitle>Marca: {{selectedProduct['Marca']}}</mat-card-subtitle>
<mat-card-title>{{selectedProduct['Nombre']}}</mat-card-title>
<mat-card-content>
<p>Código interno: {{selectedProduct['ID']}}</p>
<p>Sabor: {{selectedProduct['Sabor']}}</p>
<p>Envase: {{selectedProduct['Envase']}}</p>
<p>Línea: {{selectedProduct['Linea']}}</p>
</mat-card-content>
<button mat-raised-button routerLink="/crear-pedido" color="primary">Cerrar</button>
</mat-card>
問題是,當您單擊 ID 時,卡出現但它完全是空的。
我對 Angular 很陌生,并且很難弄清楚整個 Observable<> 和嚴格型別的考驗。我不得不補充:
"noImplicitAny": false,
到 tsconfig.json 檔案以使其編譯。我相當確定正確的語法是:
selectedProduct.Marca
而不是 selectedProduct['Marca']
但如果我這樣做,我會收到以下錯誤:
Property 'Marca' does not exist on type 'Observable<Producto_interface>'.ngtsc(2339)
我已經檢查了十幾個關于類似問題的不同執行緒,但是在嘗試了每一個解決方案之后,這就是我所取得的進展。
幫幫我,Stackoverflowers。你是我唯一的希望。
uj5u.com熱心網友回復:
您有一個要顯示的 Observable,這意味著您必須使用異步管道:
<mat-card-subtitle>Marca: {{(selectedProduct|async)?.marca}}</mat-card-subtitle>
將訂閱 selectedProduct 然后顯示 marca 屬性的值。
或者您必須將它與本地變數一起使用,但要正確命名:
*ngIf="selectedProduct | async as product"
然后在 HTML 塊中使用它:
<mat-card-subtitle>Marca: {{product?.marca}}</mat-card-subtitle>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/490045.html
