【发布时间】:2022-01-08 19:00:29
【问题描述】:
在我的项目中,我从 API(行程实体)获取数据。这是我的模型:
//Trip.model.ts
export class Trip{
created_at?:Date;
updated_at?:Date;
.... bunch of fields
}
在我的组件中,我正在获取数据并将其分配给 trips 变量。但是,当我尝试访问 trips 数组中的任何项目时,我得到“未定义”。我也无法遍历它,我尝试了 forEach 和 for...in/of。
我尝试使用接口而不是类,但没有运气。如何遍历该对象数组以使用其中的数据?
组件代码:
userName:string='';
trips:Trip[]=[];
moment:any=moment;
usersData:any={};
constructor(private auth: AuthService,
private storage: LocalStorageService,
private translate: TranslateService,
private tripService: TripService){}
ngOnInit(): void {
console.log(this.translate.currentLang)
this.userName=localStorage.getItem('username')!;
this.fetchTrips();
this.fetchPics();
}
fetchTrips() {
this.tripService.getTrips().subscribe({
next: data => {
data[0].data.forEach((value) => {
let trip: Trip = plainToInstance(Trip,value);
this.trips.push(trip);
});
}, error: error => {
console.log(error);
}
});
}
//fetchPics because I want to extract
//user's profile pics' urls from the trips array
fetchPics(){
console.log(this.trips);
console.log(this.trips[0]);
this.trips.forEach((trip)=>{
console.log(trip);
});
}
getTrips 服务方法:
getTrips(){
return this.http.get<any>(Api.API+Endpoints.TRIP);
}
这是当我显示的时候
console.log(this.trips)
分配后。
来自 API 的数据:
裁剪图片以使其更具可读性。
【问题讨论】:
-
您的 Trip 模型显示的是对象,而不是数组?
-
您能举例说明 getTrips sub 返回的内容吗?此外,您的代码中还有一些其他问题,但让我们将其留到下一步。
-
@MikeOne 刚刚编辑了它显示的内容,它是一个数组,对吧?
-
@MishaMashina 刚刚添加,您是这个意思吗?
标签: javascript angular typescript angular-components