[英]Best way to display data (object) in the template ANGULAR5
what is the best way to display data in template Angular5 for this case : 在这种情况下,在模板Angular5中显示数据的最佳方法是什么:
I load data from Firestore (=firebase) here: 我在这里从Firestore(= firebase)加载数据:
ngOnInit() {
this.user = this.authService.afAuth.authState;
this.user.subscribe((auth) => {
if (auth) {
this.itemService.getTestMembers(auth.uid).subscribe(testMembers => {
this.testMembers = testMembers;
});
}
});
} }
Firestore response is : [{"email":"john@gmail.com","name":"John"}]
Firestore的响应是: [{"email":"john@gmail.com","name":"John"}]
1° First solution in the template to display the name: 1°模板中的第一个解决方案以显示名称:
<span>{{testMembers[0]?.name}}</span>
Works, the name is displayed But I have an error : TypeError: _co.testMembers is undefined
作品,显示名称,但我有一个错误: TypeError: _co.testMembers is undefined
2° Second solution in the code to display the name: 2°代码中的第二个解决方案以显示名称:
userName: string;
ngOnInit() {
this.user = this.authService.afAuth.authState;
this.user.subscribe((auth) => {
if (auth) {
this.itemService.getTestMembers(auth.uid).subscribe(testMembers => {
this.testMembers = testMembers;
**this.userName = (JSON.stringify(testMembers[0].name)); <-- here**
});
}
});
What is the best solution, or perhaps there is another solution. 最好的解决方案是什么,或者还有另一种解决方案。 Thank you } 谢谢 }
There might be a delay in the service response as it is asynchronous so you should be adding a if
condition before you access the object as below 服务响应可能是延迟的,因为它是异步的,因此您应该在访问对象之前添加if
条件,如下所示
this.user.subscribe((auth) => {
if (auth) {
this.itemService.getTestMembers(auth.uid).subscribe(testMembers => {
this.testMembers = testMembers;
if(testMembers.length > 0 ) {//////////add this
this.userName = (JSON.stringify(testMembers[0].name));
}
});
}
});
You can also add condition on HTML like 您还可以在HTML上添加条件,例如
<span> {{testMembers ? testMembers[0]?.name : ' '}} </span>
As getting data may take some time and HTML excute first so this condition is help to avoid this error. 由于获取数据可能需要一些时间,并且HTML首先执行,因此这种情况有助于避免该错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.