[英]Angular2 Typescript Convert Firebase JSON to Object
The following Firebase code returns a list of products in json: 以下Firebase代码返回json中的产品列表:
firebase.database().ref('/products/').once('value');
In Angular2, what's the best way to convert this json to an array of product objects? 在Angular2中,将这个json转换为产品对象数组的最佳方法是什么?
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 我看到许多使用地图的Angular 2 http.get的引用,例如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. 但我不明白如何使用map或其他一些打字稿约定来做到这一点。
The following code works but feels sub-optimal. 以下代码有效,但感觉次优。 The get function returns an Observable array of products that can be bound to ngFor.
get函数返回一个可以绑定到ngFor的Observable产品数组。 Note the use of the Firebase once function.
请注意使用Firebase一次功能。 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: 您可以通过一次注册回调来获取数据,并在提供的参数上调用
val
方法:
ref.once("value", (snap) => {
var data = snap.val();
});
See this doc for more details: 有关详细信息,请参阅此文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.