html - Angular product-details.component.html 对象可能是 'undefined'

标签 html css angular typescript

我正在关注 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/

相关文章:

css - 解决出现滚动条时的画面跳转

angular - 无法通过在 Visual Studio Code 中为 Angular 8 项目启动来让 Chrome 调试器工作

javascript - background-position-x + 动画从右到左 + IE

html - Xpath:使用元素外部的文本从元素中提取值

javascript - 如何将父元素的高度设置为与子元素相同?

angular - PrimeNg 自动完成建议未加载

angular - 配置 gitlab-ci.yml 文件的问题。配置应执行脚本 : or a trigger: keyword

Javascript onclick 如果 iframe 存在,删除它并创建新的 iframe?

html - 使用 :after pseudo-element 的图像叠加

html - 所有 css 样式规则都从一个 div 元素中剥离,但没有从其他元素中剥离