简体   繁体   中英

Angular2 Typescript Convert Firebase JSON to Object

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?

eg Array of product objects.

products: Product[];

eg Product object.

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

I see many references to Angular 2 http.get that use map eg 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.

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);
    })
}

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM