Angular TypeError:无法读取未定义帮助我的属性“title”:(

Angular TypeError:无法读取未定义帮助我的属性“title”:(,angular,web-component,Angular,Web Component,我在写一个有棱角的项目 链接到我所做的JAVA项目,我必须将优惠券从DB导入一个组件,以便向用户查看它。 这就是为什么我创建了一个函数来执行此操作: import { Component, OnInit } from '@angular/core'; import { Coupon } from 'src/app/models/coupon'; import { ActivatedRoute } from '@angular/router'; import { CouponsService }

我在写一个有棱角的项目 链接到我所做的JAVA项目,我必须将优惠券从DB导入一个组件,以便向用户查看它。 这就是为什么我创建了一个函数来执行此操作:

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函数,该函数根据ID返回优惠券,在此我遇到一个错误:

错误类型错误:无法读取属性“title”或未定义 在Object.eval[as updateRenderer]CouponDetailsComponent.html:4

这是类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编写,如果您需要更多信息来帮助我,我很乐意将其发送到您的组件中,您从未像这样将api响应分配给优惠券变量

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

});
<h1>{{coupon?.title}}</h1>
在component.html中,可以这样绑定

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

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

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

this.couponService.getCouponByIdRest(id).subscribe(c => { this.coupon = c}, err=>{
  console.log("error:", err.message);
});
由于html是在浏览器中解析的,优惠券只有NULL,并且它的属性不是未识别的,也是相同的

要访问变量,请使用此关键字,否则它将无法识别变量

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

希望这个答案对你有所帮助!!

由于某些原因,它可以工作,但浏览器中仍然存在错误。.你知道原因吗?错误是什么吗?请在你的问题帖子中指定错误,并包括你的api响应,以便我能正确地指导你。你需要使用优惠券吗?在模板中添加标题而不是优惠券。title@MatanElbaz 原因可能是你没有用过这个钥匙。检查我的答案below@MatanElbaz我已经更新了我的答案,请检查我的更新答案