模板中的Ionic2数组访问

时间:2016-11-05 23:26:12

标签: angular ionic2 angular2-template

我试图在我的模板中显示来自控制器中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}}

提前致谢!

1 个答案:

答案 0 :(得分:4)

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

{{services?.id}}

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

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

详细了解安全导航操作员(?here以及有关ngIf指令here的详情。

相关问题