angular - 多个数据和[对象] [对象]
问题描述
我使用 mongoDB、express、angular、nodejs
我有两个问题:
1) 当我从 http 获取数据时,我进入组件 [Object][Object] 中的订阅函数
2)我认为我的订阅和取消订阅有问题,因为我一开始就得到了我需要得到的东西,但是当我做某事之后,我得到了多个数据,例如:如果我有 2 张苹果和香蕉的图片之后它将是苹果香蕉苹果香蕉我只想看到 1 个苹果和 1 个香蕉
组件.component.ts
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();
}
}
服务.service.ts
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;
})
);
菜单.module.ts
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;
}
解决方案
双数据:
我猜数据重复的原因是,您总是将新结果推送到服务中 getMeal 函数中的菜单数组。在添加新键之前(就在 for 循环之前),您应该考虑重置菜单数组。
this.menu = [];
[对象][对象]
用这条线
this.menu.push({ ...responseData[key]});
您使用扩展运算符将对象添加到菜单数组。在不知道您响应数据的结构的情况下,这对我来说似乎有点奇怪,但它可能会导致您在将其记录到控制台时看到的内容。因此,如果您想更改 this.menu 的结果中的某些内容,则应更改上述行。
结果数据的一些示例在这里可能会有所帮助。
推荐阅读
- vue.js - 更改 Vuetify 上的标题默认字体
- algorithm - 我有两种用于 fib 问题的算法,1 需要 7 milsec,而其他算法需要 6 milsec,甚至第二种算法需要两次调用自身
- ios - 如何从 STPPaymentCardTextField 获取 YYYY 格式的到期年份
- mongodb - 无法通过 Internet 路由连接到本地 mongodb
- sql - 丢弃对象时丢弃的统计信息?
- php - ElasticSearch 索引得分
- powershell - Invoke-WebRequest -Uri 路径中的变量
- python - 在 python lambda 中使用 switch case
- java - 如何从 Android 安全地正确访问 SQL DB
- delphi - for 循环的不正确行为