core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')
core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')
在console.log中,我有一个错误信息,但我无法解决这个问题...
这是错误信息
core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')
下面name
应该如何申报?
...
<ng-container *ngIf="dta && dta.PP">
...
HTML
<ng-container *ngIf="dta && dta.PP ">
<div class="card" style="width: 60%">
<div class="card-body">
<div class="row">
<div class="col">
<table class="table table-hover table-striped spaceLeft">
<tbody>
<tr>
<th>Year</th>
<td>{{ fiscalYear }}</td>
</tr>
<tr>
<th>Country</th>
<td>{{ selectedCountry.name }}</td>
</tr>
<tr>
<th>Register</th>
<td>{{ registreNational }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</ng-container>
TS
selectedCountry: Country;
ngOnInit(): void {
...
this.service.getPaysDta().pipe(
takeUntil(this.unsubscribe$)
).subscribe((countries) => {
this.countries = countries;
let selectedCountry = this.countries.find(c => c.id == this.country);
if (selectedCountry) {
this.selectedCountry = selectedCountry;
}
});
}
Country.ts
export class Country {
id : string;
name: string;
}
我不知道如何正确声明变量name
...:S
感谢您的帮助。
默认情况下 selectedCountry
未定义,仅在异步 getPaysDta()
订阅回调中为其分配一个值。
在 HTML 你的字符串中插入 {{ selectedCountry.name }}
。最初它将尝试访问 undefined
的 name
属性,因此出现错误消息。
您可以很容易地解决这个问题,方法是用 *ngIf
.
包装字符串插值
示例:
<td>
<span *ngIf="selectedCountry">{{ selectedCountry.name }}</span>
</td>
在console.log中,我有一个错误信息,但我无法解决这个问题...
这是错误信息
core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading 'name')
下面name
应该如何申报?
...
<ng-container *ngIf="dta && dta.PP">
...
HTML
<ng-container *ngIf="dta && dta.PP ">
<div class="card" style="width: 60%">
<div class="card-body">
<div class="row">
<div class="col">
<table class="table table-hover table-striped spaceLeft">
<tbody>
<tr>
<th>Year</th>
<td>{{ fiscalYear }}</td>
</tr>
<tr>
<th>Country</th>
<td>{{ selectedCountry.name }}</td>
</tr>
<tr>
<th>Register</th>
<td>{{ registreNational }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</ng-container>
TS
selectedCountry: Country;
ngOnInit(): void {
...
this.service.getPaysDta().pipe(
takeUntil(this.unsubscribe$)
).subscribe((countries) => {
this.countries = countries;
let selectedCountry = this.countries.find(c => c.id == this.country);
if (selectedCountry) {
this.selectedCountry = selectedCountry;
}
});
}
Country.ts
export class Country {
id : string;
name: string;
}
我不知道如何正确声明变量name
...:S
感谢您的帮助。
默认情况下 selectedCountry
未定义,仅在异步 getPaysDta()
订阅回调中为其分配一个值。
在 HTML 你的字符串中插入 {{ selectedCountry.name }}
。最初它将尝试访问 undefined
的 name
属性,因此出现错误消息。
您可以很容易地解决这个问题,方法是用 *ngIf
.
示例:
<td>
<span *ngIf="selectedCountry">{{ selectedCountry.name }}</span>
</td>