【问题标题】:TypeError: undefined is not an object (evaluating 'ctx.item.Street') (NativeScript)TypeError: undefined is not an object (evalating 'ctx.item.Street') (NativeScript)
【发布时间】:2020-08-21 01:38:38
【问题描述】:

我附加了一个数据库,该数据库将 JSON 数据提供给 NativeScript

在能够从MongoDB 提取数据、将数据路由到arrays,然后在应用程序的每个HTML 视图中显示数据方面,我已经取得了很大进展。

问题
Item 元素被认为是 undefined 但是当我 console.log() Item 在执行检索和分配功能后,我得到了确切的 JSON 元素

{
  "_id": "5f3c82f37cdb5d6766c73217",
  "Street": "134 Marin Drive",
  "City": "ABSECON",
  "Zip": "08201"
}

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

<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

现在我知道了这个代码正确输出和查看数据的事实,但我仍然收到这个错误,这会导致应用程序的非模拟 iPhone 运行崩溃。因此,如果有人对如何正确显示这些数据有任何建议,我们将不胜感激。

【问题讨论】:

    标签: javascript html json reactjs nativescript


    【解决方案1】:

    事件的疯狂转折。花了太长时间,但想出了一个解决方案。你可以添加一个?在对象变量名之后如

    <Label class="h2" [text]="item?.Street"></Label>
    

    ?. (Elvis 运算符)表示模板字段是可选的,如果未定义,则应忽略表达式的其余部分。

    参考。 https://forum.ionicframework.com/t/problems-with-json-processing-undefined-is-not-an-object/49428

    【讨论】: