gpt4 book ai didi

json - Ionic 2 Angular 2 JSON - 无法读取未定义的属性 'x',但 x.field 有效

转载 作者:行者123 更新时间:2023-12-04 18:23:54 26 4
gpt4 key购买 nike

在 Ionic2 项目中,我有一个页面“A”调用提供 JSON 文件结果的服务。在“A”页面中,我能够读取每个 JSON 元素的所有字段,并在 HTML 中显示它们。然后,我需要在另一个页面“B”中显示其中一些字段,因此使用此元素(参数)之一推送此页面。在页面“B”中,我无法直接从 HTML 中读取元素的字段。唯一可行的方法是分别阅读每个字段。我给你举个例子:

测试.json:

{
"elements" : [
{ "name":"Max",
"age":"23"},
{ "name":"John",
"age":"31"}
]}

提供者 GET 调用:

getElements(){
return this.http.get('test.json').map(res => res.json());
}

页面A getjson:

public myelements: any;
loadElements(){
this.getjson.getElements().subscribe(
result => {
this.myelements=result.elements;
}
);
}

在页面 A 中这可以正常工作:

<div class="row" *ngFor="let ele of myelements" (click)="goToPageB(ele)">
{{ele.name}} and {{ele.age}}</div>

这个(点击)函数是:

goToPageB(ele) {
this.navCtrl.push(PageB,
{ele: ele}
)
}

在页面 B 中,一种方法不起作用,另一种方法起作用。我不明白为什么:

public myele: any; // the best way, not work
public myname: any; // the other way, works

ionViewDidLoad() {
this.myele = this.navParams.get('ele'); // the best way, but error
//this.myname = this. navParams.get('ele').name; // this worse way works

最后,在B页的html中,如果我用最好的方式:

<div>{{myele.name}} </div> 
<!-- error: Cannot read property 'name' of undefined -->

如果我使用其他方式,它会起作用:

<div> {{myname}}</div>

我真的不明白为什么我不能直接使用元素。

最佳答案

尝试将其更改为:

<div>{{myele?.name}} </div> 

关于json - Ionic 2 Angular 2 JSON - 无法读取未定义的属性 'x',但 x.field 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41932604/

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