3

The following Firebase code returns a list of products in json:

firebase.database().ref('/products/').once('value');

In Angular2, what's the best way to convert this json to an array of product objects?

e.g. Array of product objects.

products: Product[];

e.g. Product object.

export class Product {
    public id: string;
    public name: string;
}

I see many references to Angular 2 http.get that use map e.g. https://angular.io/docs/ts/latest/guide/server-communication.html#!#sts=More%20fun%20with%20Observables

getHeroes (): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

But I don't understand how to use map or some other typescript convention to do this.

3
  • What does the "list of products" look like? Commented Jul 6, 2016 at 15:12
  • Updated question to clarify what an array/list of product objects might look like. Commented Jul 9, 2016 at 15:18
  • ...Just found an answer here: stackoverflow.com/a/41752653/7467098 Commented Jan 25, 2017 at 4:07

2 Answers 2

1

The following code works but feels sub-optimal. The get function returns an Observable array of products that can be bound to ngFor. Note the use of the Firebase once function. This is really a data snapshot and not a data stream.

this.products = get();

template:

<div *ngFor="let product of products">
    <div>{{product?.id}}</div>
</div>

function:

get(): Observable<Wishlist[]> {

    return Observable.fromPromise(
        firebase.database().ref('products').once('value')
    ).flatMap(snapshot => {
        let objects = snapshot.val();
        let products: Array<Product> = new Array();
        for (let key in objects) {
            let object = objects[key];
            let product: Product = new Product(key, object.name);
            products.push(product);
        }
        return Observable.of(products);
    })
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could get data by registering a callback on once and call the val method on the provided parameter:

ref.once("value", (snap) => {
  var data = snap.val();
});

See this doc for more details:

1 Comment

Understood, but how is this json mapped to an object?

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.