2016-09-25 124 views
0

我對mongodb很新。我基本上試圖從一個集合中檢索數據並放到屏幕上。它是一個angular2-meteor應用程序。我可以在mongo shell中插入和檢索數據。但是,當我通過價值書籤嘗試循環我得到的錯誤:無法使用ngFor與angular2顯示Mongodb收集數據到angular2流星

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

當我安慰從find()方法日誌返回的數據,它返回整個MongoDB的對象集合和boomarks收集深埋在物體內部。

如何獲取使用.find()方法返回的返回書籤變量中的所有對象的數組?

我的分量如下:

import { Component } from '@angular/core'; 
import template from './bookmarks.component.html'; 
import { Bookmarks } from '../../../../collections/bookmarks'; 
import { Mongo } from 'meteor/mongo'; 
@Component({ 
    selector: 'bookmarks-list', 
    template 
}) 
export class bookmarksListComponent { 
    bookmarks: Mongo.Cursor<Object>; 
    constructor() { 
    this.bookmarks=Bookmarks.find(); 
    console.log(this.bookmarks); 
    } 
} 

這裏是HTML模板:

<tbody> 
    <tr *ngFor="let bookmark of bookmarks"> 
     <td>{{bookmark.title}}</td> 
     <td>{{bookmark.url}}</td> 
     <td>{{bookmark.category}}</td> 
     <td><button class="btn btn-danger">Delete</button></td> 
    </tr> 
</tbody> 

Error Snapshot

回答

2

發現了使用rxjs解決方案: 而不是正與流星/蒙戈,使用rxjs並訂閱mongo的collections.find()方法。也同時newing了蒙戈集合使用MongoObservable.collections整個代碼:

bookmarks.component.ts:

import "reflect-metadata"; 
import { Component, OnInit, NgZone } from '@angular/core'; 
import template from './bookmarks.component.html'; 
import { Bookmarks, bookmark } from '../../../../collections/bookmarks'; 
import { Observable } from 'rxjs'; 
@Component({ 
    selector: 'bookmarks-list', 
    template 
}) 
export class bookmarksListComponent implements OnInit{ 
    private bookmarks: bookmark[]; 
    constructor(private zone: NgZone) { 
    } 
    ngOnInit(){ 
    Bookmarks.find({}).zone().subscribe({ 
     next: bookmarks => { 
     console.log("Got Bookmarks: ", bookmarks); 
     this.bookmarks=bookmarks; 
     } 
    }); 
    } 
} 

Bookmarks.ts(集合)

import { MongoObservable } from 'meteor-rxjs'; 
export interface bookmark { 
    title: string; 
    url: string; 
    category: string; 
} 
export const Bookmarks= new MongoObservable.Collection<bookmark>('bookmarks'); 

Angular2- rxjs-meteor: 從這個回購協助中獲得幫助https://github.com/ijager/meteor-rxjs-angular2.0.0-example.git

+0

的是不是沒有錯的語法? 'Bookmarks.find({}).zone()。subscribe({'爲什麼'{'? – ATX

0

如果你真的想使用Mongo.Cursor做到這一點,然後在你的代碼

constructor() { 
this.bookmarks=Bookmarks.find(); 
console.log(this.bookmarks); 
    } 

更換this.bookmarks=Bookmarks.find();

this.bookmarks=Bookmarks.find({}).fetch();