[英]TypeError: undefined is not an object (evaluating 'ctx.item.Street') (NativeScript)
I've attached a database that feeds JSON data to NativeScript
.我附加了一个数据库,该数据库将 JSON 数据提供给NativeScript
。
I've gotten pretty far in terms of being able to pull the data from MongoDB
, routing the data into array
s, and then display the data in each HTML
view of the app.在能够从MongoDB
中提取数据,将数据路由到array
s,然后在应用程序的每个HTML
视图中显示数据方面,我已经取得了相当大的进展。
Issue :问题:
The Item
element is considered undefined
yet when I console.log()
the Item
after doing the retrieve and assign function, I get the exact JSON element当我在执行检索并分配 function 后console.log()
Item
时, Item
元素被认为是undefined
的,我得到了确切的 JSON 元素
{
"_id": "5f3c82f37cdb5d6766c73217",
"Street": "134 Marin Drive",
"City": "ABSECON",
"Zip": "08201"
}
JS JS
export class ItemDetailComponent implements OnInit {
item: Item;
constructor(
private itemService: ItemService,
private route: ActivatedRoute,
) {}
ngOnInit(): void {
const id = this.route.snapshot.params.id;
this.itemService.getItem(id).then(item => {
this.item = item;
console.log(this.item);
});
}
}
HTML HTML
<FlexboxLayout class="m-15">
<Label class="h2" [text]="item.Street"></Label>
<Label class="h2" [text]="item.City"></Label>
<Label class="h2" [text]="item.Zip"></Label>
</FlexboxLayout>
https://imgur.com/a/JQeyz9t https://imgur.com/a/JQeyz9t
Now I know for a fact that this code properly outputs and views the data yet I still get this error which would crash the non-emulated iPhone
run of the app.现在我知道了这个代码正确输出和查看数据的事实,但我仍然收到这个错误,这会导致应用程序的非模拟iPhone
运行崩溃。 So if anyone has advice on how to properly display this data it would be much much appreciated.因此,如果有人对如何正确显示这些数据有任何建议,将不胜感激。
Wild turn of events.风云变幻。 Took way too long but figured out a solution.花了太长时间,但想出了一个解决方案。 You can add a?可以加一个吗? after the object variable name such as object 之后的变量名如
<Label class="h2" [text]="item?.Street"></Label>
The?.这?。 (Elvis operator) means that the template field is optional and if undefined, the rest of the expression should be ignored. (Elvis 运算符)表示模板字段是可选的,如果未定义,则应忽略表达式的 rest。
Ref.参考。 https://forum.ionicframework.com/t/problems-with-json-processing-undefined-is-not-an-object/49428 https://forum.ionicframework.com/t/problems-with-json-processing-undefined-is-not-an-object/49428
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.