0

I'm using Angular2 and I have retrieved some data from Firebase in this way:

dataset: any;
onGetData() {
    this._dataService.getAllData()
        .subscribe(
        data => this.dataset = JSON.stringify(data),
        error => console.error(error)
    );

if I print dataset I get this JSON:

{"-KE8XuCI7Vsm1jKDJIGK":{"content":"aaa","title":"bbb"},"-KE8XvM268lWhXWKg6Rx":{"content":"cccc","title":"dddd"}}

How can I print out a list made up of only the title values from this JSON array?

I'd like to have: bbb - dddd

splunk
  • 6,435
  • 17
  • 58
  • 105

2 Answers2

2

You can only iterate over an array using ngFor. In your case you need to implement a custom pipe to iterate over keys of an object.

Something like that:

@Pipe({name: 'keyValues'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]);
    }
    return keys;
  }
}

and use it like that:

<span *ngFor="#entry of dataset | keyValues">           
  Title: {{entry.value.title}}
</span>

See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
0

In your view you need

<div *ngFor='#data of dataset'>
    {{ data.title }} -
</div>
Austin
  • 1,291
  • 10
  • 19
  • it doesn't work. I had already tried in this way:http://stackoverflow.com/questions/36339173/cant-show-data-retrieved-from-firebase?noredirect=1#comment60309480_36339173 but I got that error. I also tried adding a pipe MapToIterable but it still didn't work – splunk Apr 01 '16 at 19:58
  • oh, that's because the dataset is not an array. You'll need it to be an array to loop through the data like that – Austin Apr 01 '16 at 20:00
  • I get this error in the console: Error: Cannot find a differ supporting object '{"-KE8XuCI7Vsm1jKDJIGK.... I tried with dataset: Object[] rather than dataset:any but It gives me error on this line: data => this.dataset = JSON.stringify(data) – splunk Apr 01 '16 at 20:08