2017-03-13 25 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