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

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

Comments

0

In your view you need

<div *ngFor='#data of dataset'>
    {{ data.title }} -
</div>

3 Comments

it doesn't work. I had already tried in this way:stackoverflow.com/questions/36339173/… but I got that error. I also tried adding a pipe MapToIterable but it still didn't work
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
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.