2017-01-18 93 views
3

我想在Angular 2中使用ngFor將Firebase查詢的結果綁定到我的模板。這很容易在下面實現。適用於Firebase列表的嵌套Angular2 ngFor指令

組件:

export class FeaturedThreadsComponent { 
    threads: FirebaseListObservable<any[]>; 
    qualitySubject: Subject<any>; 

    constructor(af: AngularFire) { 
     this.qualitySubject = new Subject(); 
     this.threads = af.database.list('/threads', { 
      query: { 
       orderByChild: 'quality', 
       endAt: 5 
      } 
     }); 
    } 
} 

模板:

<div *ngFor="let thread of threads | async"> 
    {{thread.title}} 
</div> 

但是,如果我想使用其他ngFor指令嵌套在模板中列出的子對象的鑰匙......

<div *ngFor="let thread of threads | async"> 
    {{thread.title}} 
    <div *ngFor="let participant of thread.participants"> 
     {{participant.$key}}} 
    </div> 
</div> 

我得到控制檯錯誤,Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

在我的數據庫結構中,participantsthread的子項,它是threads的子項,其中thread是動態項。所以我不能使用participants的直接路徑。

嵌套ngFor指令的這種模式在僅通過本地文件迭代的服務中正常工作。爲什麼它不在這裏工作似乎對我有點模糊。

+0

我不這麼認爲。如果我使用實際的鍵'{{participant.adam}}',我會得到相同的控制檯錯誤。我懷疑這與試圖迭代Angular 2不能識別爲數組的對象'參與者'有關。 –

+0

'thread.participants'將是一個對象,並且將不可用'ngFor'進行迭代。這是核心問題,被引用問題的答案應該可以幫助你。 – cartant

+0

它是'threads:FirebaseListObservable ;'將線程'存儲爲一個可迭代的數組?這似乎是有道理的。這意味着這個問題更像是一個特定於Firebase/Angularfire2的使用問題。因爲我需要一種方法,當''參與者'是一個動態密鑰的子節點,它不能以直接路徑暴露時,它就成爲一個可觀察數組。 –

回答

1

對於那些追隨此線程的人被標記爲重複的人,請不要像接受的答案建議那樣創建管道。 The best answer避免了被接受的答案的performance issues,並且簡單得多。