使用数据库中的角度5从数据库中获取空对象?

时间:2018-02-16 19:22:55

标签: javascript firebase firebase-realtime-database angularfire2 angular5

你好,我有一个小问题,我不知道如何解决,我之前已经问了一个问题,因为事情对我来说并不明显,但他们现在,here,我会写我的代码和试着解释一下我想要实现的目标。

这是我数据库中的数据:

create table #thing ( id int ); --id is PK
create table #ext ( id varchar(1) ); -- id is PK
create table #thingext ( thing int, ext varchar(1) ); -- thing,ext is PK
create table #parent ( id varchar(1), ext varchar(1)); -- id is PK, ext is FK
create table #thingparent ( thing int, parent varchar(1)); -- thing,parent is PK

insert into #thing values (0),(1),(2),(3),(4),(5);
insert into #ext values ('m'),('s'),('q'),('z');
insert into #thingext values (0,'m'),(1,'m'),(2,'s'),(3,'s'),(4,'q'),(5,'z');
insert into #parent values ('a','m'),('b','q');
insert into #thingparent values (0,'a'),(1,'a'),(2,'a'),(3,'a'),(4,'b'),(5,'b');

select t.id as childid, p.ext as extid
from #thing t
join #thingparent tp on t.id = tp.thing
join #parent p on tp.parent = p.id

我在app.component.ts中获取数据:

posts 
     --- 1 
          --- puslisher -- "Erick" 
          --- content :   "Something is written here"
          --- comments 
                      --- 1
                           --- comment : "Yes"
                           --- commentator : "Patrick"  
                      --- 2 
                           --- comment : "I dont think so "
                           --- commentator : "Sarah"
     --- 2 
          --- puslisher -- "Patrick" 
          --- content :   "News here .."
          --- comments 
                      --- 1
                           --- comment : "Yes"
                           --- commentator : "Ines"  

这是我的HTML代码:

export class AppComponent implements OnInit {

    pubs:Observable<any[]>;
    constructor(private db:AngularFireDatabase){
    }
    ngOnInit(){
       this.pubs = this.getData('/posts');
    }

    getData(path):Observable<any[]>{
       return this.db.list(path).valueChanges()
    }

}

但是你可以看到我的第一个对象是空的,这导致问题:

<div *nfFor="let post of pubs | async ">
    <p>publisher {{post.publisher}}</p>
    <p>content : {{post.content}}</p>
    <div>{{post.comments}}</div>
    <ul> 
       <li *ngFor="let cmt of post.comments" >{{cmt?.comment}}</li>
    </ul>
</div>

这导致我在图片中看到的问题。

enter image description here

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

那是因为你正在使用{{post.comments}},它在内部调用 Object.toString()方法,该方法返回** [object Object] **。 因此,您需要使用json管道对对象进行字符串化并显示它。

请尝试以下代码。

<div *nfFor="let post of pubs | async ">
    <p>publisher {{post.publisher}}</p>
    <p>content : {{post.content}}</p>
    <div>{{post.comments | json}}</div>
    <ul> 
       <li *ngFor="let cmt of post.comments" >{{cmt?.comment}}</li>
    </ul>
</div>