typescript Angular2 打字稿如何获取对象属性以显示在模板中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38072767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 typescript how to get object properties to display in template
提问by Thinker
I am learning angular2 and typescript and wondering why I can not access property values of the object in my template.
我正在学习 angular2 和 typescript,想知道为什么我无法访问模板中对象的属性值。
My component:
我的组件:
export class Farm{
data:JSON;
id: any;
constructor(private nextService: NextService, navParams: NavParams){
this.id = navParams.get("param1");
}
getFarmDetails(){
this.data = this.nextService.fetchData(this.id)
console.log(this.data)
}
}
where console.log(this.data) gives me Object {id: 1, name: "Leanne Graham", username: "Bret", email: "[email protected]", address: Object…}
console.log(this.data) 在哪里给我 Object {id: 1, name: "Leanne Graham", username: "Bret", email: "[email protected]", address: Object…}
In my template I have
在我的模板中,我有
<div>
{{data}}
</div>
which outputs on my screen as [object Object]
在我的屏幕上输出为 [object Object]
How can I instead output properties like email or username?
我如何才能输出诸如电子邮件或用户名之类的属性?
UPDATE: If I do like {{data.email}} I get following error:
更新:如果我喜欢 {{data.email}},我会收到以下错误:
回答by toskv
You can access those properties as you would in javascript.
您可以像在 javascript 中一样访问这些属性。
For example:
例如:
{{data.email}}
If the data is retrieved asynchronously you can use the elvis operator ?.to avoid the errors while data is null.
如果数据是异步检索的,您可以使用 elvis 运算符?。避免数据为空时的错误。
{{data?.email}}