【发布时间】:2021-12-30 19:42:32
【问题描述】:
当我尝试访问数组时,它返回undefined。
就好像我收到的内容在另一个元素中,因为在控制台中,数组不是直接访问的,而是您必须打开一个选项卡才能看到它。
Console.logs
查看 Postman 上的 json 响应:
json response
这是组件的代码:
fetchHolidays(){
this.calendarService.fetchDates(this.year)
.subscribe((dates)=>{
console.log(dates);
console.log(dates.length);
console.log(dates[0]);
this.holidays=dates;
this.updatedVariables=true;
}, (err) => {
console.log(err)
//this.holidays=[];
}
);
}
这是模型日历的代码:
export class Calendar{
public date: string= '';
public type: TypeDate = new TypeDate;
}
export class TypeDate{
public id: number = 0;
public descripcion: String = '';
}
这是我的服务代码:
public fetchDates(year: number): Observable<Calendar[]>{
const url = `${this.baseUrl}${year}`;
return this.httpClient.get<Calendar[]>(url);
}
我尝试通过更改模型来提取数据:
export class ContentCalendar{
public calendar: Calendar[]=[];
}
export class Calendar{
public date: string= '';
public type: TypeDate = new TypeDate;
}
export class TypeDate{
public id: number = 0;
public descripcion: String = '';
}
在我的组件中:
fetchHolidays(){
this.calendarService.fetchDates(this.year)
.subscribe((contentCalendar)=>{
console.log(contentCalendar);
console.log(contentCalendar['calendar'][0]['date'])
console.log(contentCalendar.calendar[0].date);
错误是Cannot read properties of undefined (reading '0')
Console object information
【问题讨论】:
标签: arrays angular typescript service return-type