【发布时间】:2022-01-24 10:41:33
【问题描述】:
我正在尝试在前端显示我的数据(食谱)。当我从服务器获取 console.log(data) 时,我有一个对象,其属性为“msg”,其中包含对象数组。
我可以使用
data['msg' as keyof typeof data])
访问该数组
所以当我 console.log 我得到一个对象数组
logging msg property of data
现在我的问题是当我尝试将该数组分配给
this.recipe
数组时。
当我尝试
this.recipe = data['msg' as keyof typeof data]
时出现错误:
类型“Function”缺少类型“Recipe[]”中的以下属性:pop、push、concat、join 等 27 个。
但是当我尝试使用 push() 时,我得到了
“功能”类型缺少“配方”类型的以下属性:描述、成分
我对 Angular 比较陌生,我迷路了。 如果您需要我的其他代码块,现在让我来,我不想复制粘贴很多,因为我不确定问题出在哪里,什么会有帮助。我把文件放在这里问题。
我遇到问题的代码:
export class ListComponent implements OnInit {
public recipes: Recipe[];
constructor(private _recipeService: RecipeService) { }
ngOnInit(): void {
this.readRecipes();
}
readRecipes() {
this._recipeService.readRecipes().subscribe({
next: (data) => {
this.recipes = data['msg' as keyof typeof data];
}
,
error: (error) => console.log(error),
complete: () => console.info('complete')
}
)
}
}
我的 recipe.service.ts 文件:
export class RecipeService {
private baseUri: string = "http://localhost:8080";
private headers = new HttpHeaders().set('Content-Type', 'application/json')
constructor(private http: HttpClient) { }
createRecipe(recipe: Recipe) {
return this.http.post(this.baseUri + '/create', recipe, { headers: this.headers });
}
readRecipes() {
return this.http.get(this.baseUri + '/read', { headers: this.headers });
}
updateRecipe(recipe: Recipe) {
return this.http.put(this.baseUri + '/update', recipe, { headers: this.headers });
}
deleteRecipe(id: string) {
return this.http.delete(this.baseUri + '/delete/' + id, { headers: this.headers });
}
}
读取路径的后端部分代码:
router.get('/read', (req, res, next) => {
Recipe.find({}, (err, recipes) => {
if (err)
res.status(500).json({
errmsg: err
});
res.status(200).json({
msg: recipes
});
});
});
-
嗨,欢迎来到 Stack Overflow。请通过将源代码和 JSON 数据附加为 sn-ps 而不是图像来提供 Minimal, Reproducible Example 。谢谢。
-
请尝试将代码上传到stackblitz
-
我编辑了我的第一篇文章,希望它现在更具可读性。谢谢