As I attempt to display my data (specifically recipes) on the frontend, I encounter an issue. When I log the data received from the server, I notice that it is an object with a 'msg' property containing an array of objects.
To access this array, I can use data['msg' as keyof typeof data]
. By doing so, I obtain an array of objects.
However, when I try to assign this array to the this.recipe
array using
this.recipe = data['msg' as keyof typeof data]
, I encounter an error:
Type 'Function' is missing the following properties from type 'Recipe[]': pop, push, concat, join, and 27 more.
Furthermore, attempting to use push() results in:
Type 'Function' is missing the following properties from type 'Recipe': description, ingredients
Being relatively new to Angular, I'm feeling lost and unsure how to resolve this issue. If additional code snippets would be helpful, please let me know. For now, I've included the file where the problem arises.
The problematic code snippet is shown below:
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')
}
)
}
}
Code for my recipe.service.ts file:
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 });
}
}
Backend portion of code for the read route:
router.get('/read', (req, res, next) => {
Recipe.find({}, (err, recipes) => {
if (err)
res.status(500).json({
errmsg: err
});
res.status(200).json({
msg: recipes
});
});
});