【发布时间】:2021-05-25 14:55:22
【问题描述】:
我有一个 Angular 项目,它从 Spring Boot 项目中获取参数。在后面我有一个包含信息的 DTO,从前面我访问该信息以将其显示在屏幕上。当我显示包含信息的对话框时,它在控制台TypeError: Cannot read property 'commit' of undefined 中显示错误,但它工作正常。
这是错误:
这是about.component.html:
<header class="title-color" fxFlex>Build Info</header>
<mat-divider></mat-divider>
<span class="header-item">Front (Angular): </span>
<div fxFlexLayout="column" class="about-data">
<div>Commit: {{data.front.commit}}</div>
<div>Fecha: {{data.front.date}}</div>
<div>Versión: {{data.front.version}}</div>
</div>
<mat-divider></mat-divider>
<span class="header-item">Back (Java): </span>
<div fxFlexLayout="column" class="about-data">
<div>Commit: {{data.people.commit}}</div>
<div>Fecha: {{data.people.date}}</div>
<div>Versión: {{data.people.version}}</div>
</div>
这是about.component.ts:
ngOnInit() {
this.http.get('/assets/build_info.txt', { responseType: 'text' }).subscribe((data: String) => {
let re: RegExp = new RegExp("^(Author|Date|commit|Version).*", "i");
let frontInfo: InfoDTO = data.split('\n').filter(l => re.test(l)).reduce((accum, line) => {
line = line.replace(":", " ");
let sepIndex = line.indexOf(' ');
let attr = line.substring(0, sepIndex).toLowerCase();
let value = line.substring(sepIndex).trim();
accum[attr] = value;
return accum;
}, new InfoDTO());
const ob1 = this.aboutService.aboutInfo();
ob1.subscribe((people: InfoDTO) => {
this.data = {
front: frontInfo,
people: InfoDTO
};
});
});
}
我找不到问题可能是什么,因为数据没问题,我不知道是什么导致了这个错误。
【问题讨论】:
-
获取数据是异步的,需要一些时间才能完成,在完成之前,当
data.front未定义时,角度尝试渲染模板。仅当data可用时,才将ngIf添加到您的html 块中 -
可以举个例子吗,不知道怎么放 ngIf 是这个
div
标签: javascript angular angular11