我正在关注 View Product Details angular网站上的教程,遇到错误:
Error in src/app/product-details/product-details.component.html (4:16) Object is possibly 'undefined'.
我无法继续下一个教程,因为它需要此页面才能运行。
代码如下:
product-list.component.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>
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
<h2>Product Details</h2>
<div *ngIf="product">
<h3>{{ product.name }}</h3>
<h4>{{ product.price | currency }}</h4>
<p>{{ product.description }}</p>
</div>
我希望有人可以帮助解决问题,因为我看到代码正在运行。
谢谢。
最佳答案
我也在做这个教程,我通过将 ProductDetailsComponent 添加到 app.module.ts 中的声明来修复它。
declarations: [
AppComponent,
TopBarComponent,
ProductListComponent,
ProductAlertsComponent,
ProductDetailsComponent //<-- add this into declarations
],
别忘了先在 app.module.ts 中导入 ProductDetailsComponent。
import { ProductDetailsComponent } from './product-details/product-details.component';
刷新整个网站后它应该可以工作(不仅仅是右侧的显示,去保存并刷新浏览器选项卡)。
关于html - Angular product-details.component.html 对象可能是 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68735333/