Angular `product-details.component.html` 对象可能是“未定义的”。
Angular `product-details.component.html` 对象可能是“未定义的”。
我正在遵循angular网站上的查看产品详情教程,但遇到了以下错误:
在src/app/product-details/product-details.component.html(4:16)中出现错误
对象可能未定义。
我无法进行下一步的教程,因为这个页面需要运作。
以下是代码:
product-list.component.html
Products
{{ product.name }}
product-details.component.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); } }
product-details.component.html
Product Details
{{ product.name }}
{{ product.price | currency }}
{{ product.description }}
我希望有人能帮助找出问题,因为我看到代码是有效的。
谢谢。
admin 更改状态以发布 2023年5月20日
我也在做这个教程,我通过在app.module.ts文件中将ProductDetailsComponent添加到declarations中来修复了它。
declarations: [ AppComponent, TopBarComponent, ProductListComponent, ProductAlertsComponent, ProductDetailsComponent //<-- add this into declarations ],
别忘了在app.module.ts中先导入ProductDetailsComponent。
import { ProductDetailsComponent } from './product-details/product-details.component';
刷新整个网站后它应该可以工作(不仅是右侧的显示,保存并刷新浏览器选项卡)。