【问题标题】:Ionic2 array access in template模板中的 Ionic2 数组访问
【发布时间】:2017-03-19 13:37:03
【问题描述】:

我正在尝试在我的模板中显示来自控制器中 json 的数据。

我发现的所有替代方案都是指使用ngFor,但我不想迭代所有项目,因为我只想显示其中一个。

getServicio(servicioId: number) {
        let getServicio = 'services?id=' + servicioId;
        this.http.getRequest(getServicio) //returns a json
            .then(
            res => {
                this.services = res[0];
            }
            )
            .catch(
            error => console.log(error)
            );
    }

在模板中我简单地写:

{{services.id}}

它给了我一个错误:

无法读取未定义的属性“id”

没有其他方法可以吗?或者以另一种方式,将所有数据传递给模板并使用如下索引进入数组:

{{services[0].id}}

提前致谢!

【问题讨论】:

  • 服务未定义,但尚未收到 HTTP 响应。使用 ngIf 避免在未定义时显示它,或使用 services?.id。顺便说一句,如果它应该是一个单一的服务,你为什么将它命名为services。为什么 getRequest 会返回一个数组,因为您传递的是要检索的唯一对象的 ID?

标签: angular ionic2 angular2-template


【解决方案1】:

问题是您试图在数据到达之前显示数据 (services.id)(http 请求是异步的) - 这意味着在呈现模板时 services.idundefined。最简单的解决方案是使用安全导航运算符 (?) 在数据到达之前“保护”您的模板:

{{services?.id}}

您也可以使用ngIf 指令,这样在定义services 之前,您要显示services 的模板部分不会呈现:

<div *ngIf="services">
    {{services?.id}}
</div>

阅读更多关于安全导航运算符 (?) here 和更多关于 ngIf 指令 here 的信息。

【讨论】:

    猜你喜欢
    • 2012-07-14
    • 2019-07-04
    • 2015-05-31
    • 2011-01-05
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多