【发布时间】:2019-11-28 04:39:43
【问题描述】:
从 Firebase 数据库保存和检索数据不会给我相同类型的数据。下面我将解释我在做什么以及我遇到了什么:
保存数据
我正在使用以下代码将 Recipe 数组保存到 Firebase 数据库:
save() {
this.http.put(
this.recipeURL,
this.recipesService.getRecipes()
).subscribe(
(response) => {
console.log(response);
}
);
}
使用RecipeService 检索Recipe 对象中的Array 的代码非常简单:
getRecipes() {
return this.recipes.slice();
}
Recipe 模型定义如下(没什么花哨的):
export class Recipe {
public id: number;
public name: string;
public description: string;
public imagePath: string;
public ingredients: Ingredient[];
constructor(id: number, name: string, desc: string, imagePath: string, ingredients: Ingredient[]) {
this.id = id;
this.name = name;
this.description = desc;
this.imagePath = imagePath;
this.ingredients = ingredients;
}
}
检索数据
之后,我使用以下代码检索数据:
read() {
this.http.get<Recipe[]>(
this.recipeURL
).subscribe((recipes) => {
console.log(recipes);
console.log(this.recipesService.getRecipes());
})
}
结果/问题
在代码中,我记录了 get 方法的响应以及我想要替换的 Recipe 对象的原始列表。看来我正在检索 Array 的 Json 对象,而不是 Recipe 对象。当您查看控制台输出时,您会在下面找到两者之间差异的屏幕截图。
如您所见,一个是{...} 的Array,另一个是Recipe 的Array。
希望有人可以帮助解释/解决这个问题。问题是,在分配从 Firebase 数据库获取的数据并更新应用程序(使用 Subject)后,我的页面没有显示新数据,而是一直显示旧数据。
【问题讨论】:
-
你能在
recipesService中分享getRecipes函数吗? -
@ahmeticat:添加了代码。没什么特别的。在
RecipeService中,实际数据保存为Recipe[] -
你能用
changeDetection吗?
标签: json angular typescript http get