我的Angular4应用程序上的Firebase Object to array

时间:2018-02-08 10:34:24

标签: angular firebase firebase-realtime-database angularfire2

我试图在我的应用中使用* ngFor来遍历我的数据库以从每个PostId获取数据

这就是它被推入我的firebase数据库的方式

 create(post) {
    return this.db.list('/posts').push(post);
  }

这是我从数据库中获取它的方式

 get(postId) {
    return this.db.object('/posts/' + postId);
  }

这是它存储在我的firebase数据库中的方式

"posts" : {
    "-L4mKOzN9UZ3ls10ED5h" : {
      "body" : "Pureed squash and sweet potatoes are some of the handiest ingredients to have around your kitchen in the fall and winter months. .",
      "imageUrl" : "https://32lxcujgg9-flywheel.netdna-ssl.com/wp-content/uploads/2013/12/butternut-Squash-Blue-Cheese-Pizza-8.jpg",
      "name" : "tolulope",
      "title" : "Butternut Squash Pizza with Blue Cheese"
    }
  },

这就是我在HTML中使用它的方式

 <div class="row" *ngFor="let post of post$ | async">
      <div class="col-lg-4 mb-4">
          <div class="view overlay hm-white-slight waves-light" mdbRippleRadius>
               <img src="{{ post.imageUrl }}" alt="First sample image">
               <a>
                <div class="mask"></div>
                    </a>
                </div>
            </div>

以下是错误消息

  

尝试区分'tolulope'时出错。只允许数组和迭代

2 个答案:

答案 0 :(得分:0)

查看以下代码段。

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  posts = `{
    "posts": {
        "-L4mKOzN9UZ3ls10ED5h": {
            "body": "Pureed squash and sweet potatoes are some of the handiest ingredients to have around your kitchen in the fall and winter months. .",
            "imageUrl": "https://32lxcujgg9-flywheel.netdna-ssl.com/wp-content/uploads/2013/12/butternut-Squash-Blue-Cheese-Pizza-8.jpg",
            "name": "tolulope",
            "title": "Butternut Squash Pizza with Blue Cheese"
        }
    }
}`;
  objectKeys;
  ngOnInit() {

    this.objectKeys = Object.keys;
    this.posts = JSON.parse(this.posts).posts;
    console.log(this.posts);

  }



}

<强>组件

<div class="row" *ngFor="let post of objectKeys(posts) ">
    <div class="col-lg-4 mb-4">
        <div class="view overlay hm-white-slight waves-light" mdbRippleRadius>
            <img src="{{ posts[post].imageUrl }}" alt="First sample image">
            <a>
                <div class="mask">{{posts[post].body}}</div>
            </a>
        </div>
    </div>

<强> WORKING DEMO

答案 1 :(得分:0)

尝试

<ng-container *ngIf="post$ | async; let post; else othercontent">
    <div class="row" >
        <div class="col-lg-4 mb-4">
            <div class="view overlay hm-white-slight waves-light" mdbRippleRadius>
                <img src="{{ post.imageUrl }}" alt="First sample image">
                <a>
                    <div class="mask"></div>
                </a>
            </div>
        </div>
    </div>
</ng-container>
<ng-template #othercontent>Loading Post...</ng-template>

你不能用*ngFor对象,希望你阅读评论。