2017-03-13 27 views
2

我正在使用AngularFire2,嘗試從列表中獲取列表。 甲嵌套*有* ngFor內ngFor上不顯示視圖...AngularFire2嵌套* ngFor Array中的數組...但Firebase沒有數組... ...?

app.componnent

... 
constructor(private _af: AngularFire) { 
    this.lists = this._af.database.list(this._API_URL); 
} 
... 

app.component.html

<div *ngFor="let list of lists | async"> 
    {{sublist.name}}<br/> <!-- I can see you --> 

    <!--******* I can't see you **********--> 
    <div *ngFor="let rootword of list.rootwords"> 
     {{rootword.word}} {{rootword.total}} 
    </div> 
</div> 

火力地堡

的實施例
maindb 
    |_list1 
    | |_name: 'List 1" 
    | |_rootwords 
    |  |_apple 
    |  | |_word: 'apple' 
    |  | |_total: 4 
    |  | 
    |  |_banana 
    |  | |_word: 'banana' 
    |  | |_total: 2 
    |  |_carpet 
    |  | |_word: 'carpet' 
    |  | |_total: 21 
    | 
    |_list2 
    |_name: "List 2" 
    |_rootwords 
     |_elephant 
     | |_word: 'elephant' 
     | |_total: 4 
     |_sloth 
      |_word: 'sloth 
      |_total: 5 

你如何在ngFor中嵌套一個ngFor與firebase.list? 我需要映射還是過濾? AngularFire2有辦法將內部對象轉換爲數組嗎?

所有建議讚賞!

回答

2

您可以使用map opereratorArray.prototype.reduce,像這樣的陣列替換rootwords對象:

import 'rxjs/add/operator/map'; 

constructor(private _af: AngularFire) { 

    this.lists = this._af.database 
    .list(this._API_URL) 

    // Use map the map operator to replace each item in the list: 

    .map(list => list.map(item => ({ 

     // Map to a new item with all of the item's properties: 
     ...item, 

     // And replace the rootwords with an array: 
     rootwords: Object.keys(item.rootwords) 

     // Use reduce to build an array of values: 
     .reduce((acc, key) => [...acc, item.rootwords[key]], []) 
     }) 
    )); 
} 

,或在不擴散語法:

import 'rxjs/add/operator/map'; 

constructor(private _af: AngularFire) { 

    this.lists = this._af.database 
    .list(this._API_URL) 
    .map(list => list.map(item => { 
     var copy = Object.assign({}, item); 
     copy.rootwords = Object.keys(item.rootwords).reduce((acc, key) => { 
      acc.push(item.rootwords[key]); 
      return acc; 
     }, []); 
     return copy; 
    })); 
} 
+0

沒有工作.. 。開始於...項目,得到一個錯誤屬性分配預期..我必須導入另一個rxjs使用此語法? 但是,如果發表評論,仍然會收到錯誤: ViewWrappedError 錯誤:./LearnComponent類中的錯誤LearnComponent - 內聯模板:19:17引起:無效參數'[object Object],[object Object],[object Object]管道'AsyncPipe' at ViewWrappedError.ZoneAwareError(http:// localhost:4200/polyfills.bundle.js:1150:33) ,[對象對象],[對象對象],[對象對象]在ViewWrappedError.BaseError [作爲構造函數] ... –

+0

已評論第二|異步,現在錯誤 - 屬性分配的預期。造成仍然是...項目 –

+0

您使用的是什麼版本的TypeScript? – cartant