網站搜尋

css - Angular product-details.component.html 物件可能為 'undefined'


我正在按照 Angular 網站上的「檢視產品詳細資訊」教學操作,並遇到了以下錯誤:

src/app/product-details/product-details.component.html (4:16) 發生錯誤:物件可能是 '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>

我希望有人能幫忙找出問題,因為我看到程式碼是正常運作的。

謝謝你。

答案#1

我也在做這個教學,我是通過將 ProductDetailsComponent 加到 app.module.ts 裡的 declarations 裡來修復它的。

declarations: [
AppComponent,
TopBarComponent,
ProductListComponent,
ProductAlertsComponent,
ProductDetailsComponent //<-- add this into declarations
],

別忘了先在 app.module.ts 中匯入 ProductDetailsComponent。

import { ProductDetailsComponent } from './product-details/product-details.component';

在刷新整個網站後應該就能正常運作(不只是右邊的顯示,要先儲存然後刷新瀏覽器分頁)。

答案#2

你可能想嘗試使用 product?.name