【问题标题】:Typescript Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays打字稿错误:找不到“对象”类型的不同支持对象“[对象对象]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays
【发布时间】:2020-11-17 10:18:29
【问题描述】:

(抱歉英语不好,我不是母语人士)
我在将值传递给对象并在 html 中显示它时遇到问题。 以下是我的代码:

  completeUserProfile = {};


  async testfunction() {
    const sampleArray = [1, 2];
    const interestRef = this.firestore.firestore.collection('interest');
    const result = interestRef.where('interestIn', 'array-contains-any', sampleArray).get();
    await result.then(querySnapshot => {
      querySnapshot.forEach(doc => {
        this.completeUserProfile[doc.data()['uid']] = {};
        this.completeUserProfile[doc.data()['uid']].uid = doc.data().uid;
        this.completeUserProfile[doc.data()['uid']].interestIn = doc.data().interestIn;
        this.completeUserProfile[doc.data()['uid']].updatedAt = doc.data().updatedAt.toDate();
        this.firestore.firestore.collection('userInformation').where('uid', '==', doc.data().uid).limit(1)
          .get().then((userInfo) => {
            userInfo.forEach(doc => {
              this.completeUserProfile[doc.data()['uid']].realName = doc.data().realName;
            })
          })
        console.log(this.completeUserProfile[doc.data()['uid']]);
      })
    });
  }

我可以在console.log 中毫无问题地看到结果。但是,我无法使用 ngFor 循环在 html 中显示我的信息。即使我只是{{completeUserProfile }},我也会得到[object Object]的结果。

在过去一个月处理 Angular 时,我意识到我必须使用 : 而不是 = 来声明对象(在本例中为 completeUserProfile)。但在这种情况下,我没有这样做。我需要帮助。感谢您抽出宝贵时间阅读本文。

【问题讨论】:

  • 您正在尝试迭代 Json 属性
  • 我是新手,我不确定您所指的 Json 属性是什么。如果您能更准确地告诉我我应该做什么,我将不胜感激。谢谢

标签: angular typescript firebase google-cloud-firestore


【解决方案1】:

ngFor 遍历arrays,错误告诉你,You are trying to iterate on a Json object.

如果你想对其进行迭代,你要么必须将其更改为数组,要么必须对键进行迭代。为此:

    completeUserProfileObject = [];
    
    this.completeUserProfileObjectKeys = Object.keys(this.completeUserProfile); // get keys
    this.completeUserProfileObject = Object.values(this.completeUserProfile); // get values

在您的 HTML 中:

<element *ngFor="let key of completeUserProfileObject">

StackBlitz

【讨论】:

    【解决方案2】:

    就像错误消息所说,普通的*ngFor 仅适用于像数组这样的可迭代对象。您正在尝试遍历一个对象。在这种情况下,您可以尝试使用keyvalue 管道(Angular v6.1+)。它返回一个对象集合,每个对象都具有keyvalue 属性。它们对应于源对象中各自的属性键和值。

    试试下面的

    <div *ngFor="let profile of completeUserProfile | keyvalue">
      {{ profile.key }}: {{ profile.value }}
    </div>
    

    因此,如果您希望在模板中渲染对象,则需要使用json 管道。

    <div> {{ completeUserProfile | json }} </div>
    

    如果您是 Angular 新手,我建议您通过他们的tutorial。它介绍了一些基础知识。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 2023-01-26
      • 2019-09-08
      • 2020-11-22
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多