【发布时间】:2017-03-25 23:18:45
【问题描述】:
我正在使用 Observables 使用 Angular 2 从 Firebase 获取数据,但是,即使我从 http 调用中获得结果,我也无法将返回的对象映射到我的实体上。
我想映射到一个食谱数组。配方是:
export class Recipe {
constructor(public name: string,
public description: string,
public imagePath: string,
public ingredients: Ingredient[]) {
}
}
包含食谱数组和对负责获取数据的服务以及订阅者的第一个调用的组件类是:
export class RecipeListComponent implements OnInit {
recipes: Recipe[] = [];
constructor(private recipeService: RecipeService) { }
ngOnInit() {
this.recipes = this.recipeService.getRecipes();
this.recipeService.recipesChanged.subscribe(
(recipes: Recipe[]) => this.recipes = recipes
);
}
}
而服务中获取数据的方法是:
fetchData() {
return this.http.get('https://...firebaseio.com/...json')
.map((response: Response) => response.json())
.subscribe(
(data: Recipe[]) => {
this.recipes = data;
console.log(data);
this.recipesChanged.emit(this.recipes);
});
数据已正确检索,但未在我的 Recipe[] 上强制转换,实际上返回的对象是这种形式:
[object Object],[object Object]
[
0: {
[functions]: ,
__proto__: { },
description: "Gioco",
imagePath: "http://....png",
ingredients: [
0: {
[functions]: ,
__proto__: { },
amount: 50,
name: "Silicone",
Symbol(observable)_g.ds6ymh8xmrz: undefined,
Symbol(rxSubscriber)_h.ds6ymh8xmrz: undefined
},
1: {
[functions]: ,
__proto__: { },
amount: 30,
name: "Plastica",
Symbol(observable)_g.ds6ymh8xmrz: undefined,
Symbol(rxSubscriber)_h.ds6ymh8xmrz: undefined
},
length: 2
],
name: "Lego",
Symbol(observable)_g.ds6ymh8xmrz: undefined,
Symbol(rxSubscriber)_h.ds6ymh8xmrz: undefined
},
1: {
[functions]: ,
__proto__: { },
description: "Peluche",
imagePath: "http://....png",
name: "Orsacchiotto",
Symbol(observable)_g.ds6ymh8xmrz: undefined,
Symbol(rxSubscriber)_h.ds6ymh8xmrz: undefined
},
length: 2
]
如何解决?
提前致谢
【问题讨论】:
-
Firebase does not store data as arrays,因此 HTTP 响应将是一个 JSON 对象。如果你打算使用简单的演员表,你应该使用
interface- 而不是class。
标签: angular firebase angular2-services angular2-http angular2-observables