【问题标题】:Multiple Objects Firebase多个对象 Firebase
【发布时间】:2017-03-28 05:02:37
【问题描述】:

我在 Firebase 中有以下数据库:

Root Categories/ID/{text:Item1 AL:Item 2 TEXT:Item 3 ...}

我有以下代码来获取我想要的“.text”或具有先前文本的项目:

this.categories = af.database.list('/categories/' + this.ID);
this.categories.subscribe(categories => console.log(categories));
this.categories.subscribe(
categories => {
    categories.map(categories =>
       console.log(categories.text),

    )
});'

Console.log 返回的正是我想要的,但是当我在 HTML 文件中检索 {{categories}} 时,它返回 Object Object

有人知道怎么解决吗?对不起我的无知我是一个完全的初学者。

【问题讨论】:

  • 尝试分配categories = JSON.parse(categories)并尝试使用typeOf(categories)检查您的categories类型

标签: javascript angular firebase firebase-realtime-database


【解决方案1】:

如果您尝试只打印{{categories}},这是预期的行为,因为categories 似乎是一个对象。如果您希望这样查看categories,则需要添加json 管道:

{{categories | json}}

但我怀疑这不是你想要的。您需要使用属性来显示categories的每个属性,例如:

{{categories.text}}

如果categories 是一个数组,请忽略上面的代码,但 json 管道在这种情况下也可以工作。如果categories 是一个数组,那么您需要迭代数组,然后从每个对象打印您想要的属性,例如

<div *ngFor="let cat of categories">
  {{cat.text}}
</div>

如果你只想选择一些特定的值,你可以在 map 中进行,并将这些值分配给一个新的数组,例如:

categoriesText: string[] = [];

this.categories.subscribe(
 categories => {
   categories.map(categories => {
      console.log(categories.text)
      this.categoriesText.push(categories.text); // push values to new array
   });
 });

然后你可以迭代那个数组:

<div *ngFor="let cat of categoriesText">
  {{cat}} <!-- here no property name as it's only a string array -->
</div>

希望这会有所帮助! :)

【讨论】:

  • 完美。完全按照我的预期工作。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-03
  • 2015-10-10
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多