gpt4 book ai didi

javascript - 在html中显示对象

转载 作者:行者123 更新时间:2023-12-02 13:49:28 25 4
gpt4 key购买 nike

我有一个返回此的查询:

enter image description here

在组件中我有以下代码:

pages: Page[];

constructor(private httpCall: HttpCall) { }

ngOnInit() {
this.httpCall.get('/pub/page/GetPageById')
.subscribe(
data => {
this.pages = <Page[]>data
console.log(data);
console.log(this.pages);
})
}

HttpCall 是我的服务,可以正常工作。

它记录了这个:

Object {Id: 6, Title: "asdasd", Content: "<p>asdasd</p>"}
Object {Id: 6, Title: "asdasd", Content: "<p>asdasd</p>"}

我的 page.ts 类

export class Page {
constructor(
private Id: number,
private Title: string,
private Content: string
) { }
}

当我写这个时,在html中:

 <h4 class="block-title">{{ pages.Title }}</h4>

<div class="about-project">
<p>{{ pages.Content }}</p>
</div>

但是它没有显示我的数据,而是记录了这些错误:

Error: Error in ./PageComponent class PageComponent - inline template:5:40 caused by: Cannot read property 'Title' of undefined TypeError: Cannot read property 'Title' of undefined ORIGINAL STACKTRACE: zone.js:390Error: Uncaught (in promise): Error: Error in ./PageComponent class PageComponent - inline template:5:40 caused by: Cannot read property 'Title' of undefined..

出了什么问题?

最佳答案

当您异步获取数据时,您的 pages 变量首先将是undefined

您可以使用elvis运算符来防止该错误:

<h4 class="block-title">{{ pages?.Title }}</h4>

<div class="about-project">
<p>{{ pages?.Content }}</p>
</div>

关于javascript - 在html中显示对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41114701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com