在模板ANGULAR5中显示数据(对象)的最佳方法

时间:2018-01-20 04:36:52

标签: javascript angular angular5

在这种情况下,在模板Angular5中显示数据的最佳方法是什么:

我从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响应为:[{"email":"john@gmail.com","name":"John"}]

模板中的第一个解决方案显示名称:

<span>{{testMembers[0]?.name}}</span>

Works,显示名称但是我有一个错误:TypeError: _co.testMembers is undefined

代码中显示名称的第二个解决方案:

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**
          });
      }
  });

什么是最佳解决方案,或者可能还有其他解决方案。谢谢   }

2 个答案:

答案 0 :(得分:1)

服务响应可能会有延迟,因为它是异步的,因此您应该在访问对象之前添加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)); 
            }
          });
      }
  });

答案 1 :(得分:1)

您还可以在HTML上添加条件,如

<span> {{testMembers ? testMembers[0]?.name : ' '}} </span>

由于获取数据可能需要一些时间并且HTML首先执行,因此这种情况有助于避免此错误。