TypeError: Cannot read property 'title' of undefined-Help me :(

TypeError: Cannot read property 'title' of undefined-Help me :(

我正在编写一个 Angular 项目 链接到我所做的 JAVA 项目,我必须将优惠券从数据库导入组件才能向用户查看。 这就是为什么我创建了一个函数来执行此操作:

import { Component, OnInit } from '@angular/core';
import { Coupon } from 'src/app/models/coupon';
import { ActivatedRoute } from '@angular/router';
import { CouponsService } from 'src/app/services/coupons.service';

@Component({
  selector: 'app-coupon-details',
  templateUrl: './coupon-details.component.html',
  styleUrls: ['./coupon-details.component.css']
})
export class CouponDetailsComponent implements OnInit {
  public coupon: Coupon;
  public constructor(private activeRoute: ActivatedRoute, private couponService : CouponsService) { }

  public ngOnInit() {
    const id = +this.activeRoute.snapshot.params.id;
    this.couponService.getCouponByIdRest(id).subscribe(c => {
    }, err=>{
      console.log("error:", err.message);
    });
  }
}

如您所见,该函数将在点击时获得一个 ID,并将我们传递给优惠券,该优惠券将向我们显示优惠券的详细信息,该函数在服务器端运行一个 JAVA 函数,该函数 returns根据id获取优惠券,这里遇到错误:

ERROR TypeError: Cannot read property 'title' or undefined
    at Object.eval [as updateRenderer] (CouponDetailsComponent.html: 4)

这是 class HTML 文件:

<div >
  <h1>Coupon Details:</h1>

  <h3>Coupon Title: {{coupon.title}}</h3> 
  <h3>Coupon Start Date: {{coupon.startDate}}</h3>
  <h3>End Date: {{coupon.endDate}}</h3>
  <h3>Category: {{coupon.category}}</h3> 
  <h3>Amount: {{coupon.amount}}</h3> 
  <h3>Description: {{coupon.description}}</h3> 
  <h3>Price: {{coupon.price}}</h3>
  <!-- <img style="width: 300px;" src="assets/imagess/products/{{product.id}}.jpg" alt="coupon"> -->
</div>
<div *ngIf="!coupon">
  <h1>Product not found</h1>
</div>
<br>
<button style="font-size: large;" onclick="history.back(-1)">Back to Our-Deals</button>

系统好像不能识别优惠券?标题? 我检查了所有内容是否正确列出并且找不到问题 如您所见,我刚开始在 angular 中写作,如果您需要更多信息来帮助我,我很乐意将其发送给

在您的 component 中,您从来没有像这样评估 apicoupon 变量的响应

 this.couponService.getCouponByIdRest(id).subscribe(c => { this.coupon = c}, err=>{
  console.log("error:", err.message);

});

在你的 component.html 中你可以像这样绑定

<h1>{{coupon?.title}}</h1>

您已从 getCouponByIdRest API 获取响应,但尚未将其分配给 coupon 变量。

由于html是在浏览器中解析的,所以优惠券只有NULL,不是未识别的,其属性相同。

为了访问变量,使用this关键字,否则无法识别变量。

this.couponService.getCouponByIdRest(id).subscribe(c => { this.coupon = c}, err=>{
  console.log("error:", err.message);
});

希望这个回答对您有所帮助!!