I use mongoDB, express, angular , nodejs
i have a 2 problems:
1) when I get the data from http i get to the subscribe function in the component [Object][Object]
2) I think that i have problem with the subscribe and the unsbscribe becuase I get in the start what i need to get but after when i do something I get Multiple data for example: if I have 2 pic of apple and banana After that it will be apple banana apple banana I want to see only 1 apple and 1 banana
export class MealMenusComponent implements OnInit, OnDestroy {
menu: Menu[] = [];
ngOnInit() {
this.subscription = this.mlService.getMeal().subscribe(res => {
this.menu = res;
console.log(this.menu); ----------->> [Object][Object]
});
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
public getMeal() {
return this.http.get('http://localhost:3000/meals')
.pipe(
map(responseData => {
for (const key in responseData) {
if (responseData.hasOwnProperty(key)) {
this.menu.push({ ...responseData[key]}); /
}
}
console.log(this.menu); ----------->> print the data correctly
return this.menu;
})
);
export class Menu {
public name: string;
public description: string;
public imagePathFront: string;
public imagePathBack: string;
public category: string;
public price: number;
constructor(name: string, description: string, imagePathFront: string, imagePathBack: string, category: string, price: number) {
this.name = name;
this.description = description;
this.imagePathFront = imagePathFront;
this.imagePathBack = imagePathBack;
this.category = category;
this.price = price;
}
1) Your getting that because you are trying to console log an array of objects. you can loop through each one and print individually or do something like console.log(this.menu[0].name)
2) The http get call( if you are using HttpClient ) should already be giving you an array of objects, which you can then assign to your menu: Menu[]
variable in your subscribe callback. Like so.
in your service.
public getMeal() {
return this.http.get('http://localhost:3000/meals');
}
in your component
this.mlService.getMeal().subscribe(menuItems => this.menu = menuItems);
then in your html you can loop through the properties of each menu item like so
<ul *ngFor="let item of menu">
<li> {{ item.name }} </li>
<li> {{ item.description}} </li>
....
</ul>