类型错误: 无法读取未定义的属性"标题"-帮助我:(



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

错误

类型错误:无法读取属性"title"或在 Object.eval 上未定义
[作为更新渲染器] (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>

系统似乎无法识别优惠券?标题? 我检查了所有内容是否正确列出,但找不到问题 如您所见,我刚刚开始用角度写作,如果您需要更多信息来帮助我,我很乐意发送它

在你的component中,你永远不会像这样断言你对coupon变量的api响应

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

在您的组件中.html您可以像这样绑定

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

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

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

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

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

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

最新更新