Estoy siguiendo el tutorial Ver detalles del producto en el sitio web angular y encontré el error:
Error en src/app/product-details/product-details.component.html (4:16) El objeto posiblemente esté 'indefinido'.
No puedo pasar al siguiente tutorial porque necesita esta página para funcionar.
Aquí está el código:
lista-de-productos.componente.html
<h2>Products</h2> <div *ngFor="let product of products"> <h3> <a [title]="product.name + ' details'" [routerLink]="['/products', product.id]"> {{ product.name }} </a> </h3> </div>producto-detalles.componente.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Product, products } from '../products'; @Component({ selector: 'app-product-details', templateUrl: './product-details.component.html', styleUrls: ['./product-details.component.css'] }) export class ProductDetailsComponent implements OnInit { product: Product|undefined; constructor( private route: ActivatedRoute, ) { } ngOnInit() { // First get the product id from the current route. const routeParams = this.route.snapshot.paramMap; const productIdFromRoute = Number(routeParams.get('productId')); // Find the product that correspond with the id provided in route. this.product = products.find(product => product.id === productIdFromRoute); } }producto-detalles.componente.html
<h2>Product Details</h2> <div *ngIf="product"> <h3>{{ product.name }}</h3> <h4>{{ product.price | currency }}</h4> <p>{{ product.description }}</p> </div>Espero que alguien pueda ayudar a resolver el problema porque veo que el código está funcionando.
Gracias.
También estoy haciendo este tutorial y lo arreglé agregando ProductDetailsComponent a las declaraciones dentro de app.module.ts.
declarations: [ AppComponent, TopBarComponent, ProductListComponent, ProductAlertsComponent, ProductDetailsComponent //<-- add this into declarations ],No olvide importar primero ProductDetailsComponent en app.module.ts.
import { ProductDetailsComponent } from './product-details/product-details.component';Debería funcionar después de actualizar todo el sitio web (no solo la pantalla a la derecha, vaya a guardar y actualice la pestaña del navegador).
Es posible que desee intentar usar product?.name
Lo arreglé agregando la importación 'ProductDetailsComponent' en 'app.module.ts'