您好,我有一个小问题,我不知道该如何解决,我之前曾问过一个问题,因为事情对我来说并不明显,但现在,here,我将编写代码并尝试解释我想要的内容以后再实现。

这是我数据库中的数据:

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"


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

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()
    }

}


这是我的HTML代码:

<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>


但是如您所见,我的第一个对象为空,这导致出现以下问题:

publisher: Erick
content : Something is written here

,[object Object],[object Object]

-
- Yes
- I don't think so



publisher: Patrick
content : News here

,[object Object]

-
- Yes


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

javascript - 使用数据库中的angular 5从数据库中获取空对象?-LMLPHP

任何帮助将非常感激。

最佳答案

那是因为您正在使用{{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>

10-07 12:41
查看更多