Issue
When I try to access to the array it returns undefined
.
It is as if what I receive were inside another element, because in the console the array is not accessed directly, but rather you have to open a tab to see it.
Console.logs
See the json response on Postman:
json response
That's the code of the component:
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=[];
}
);
}
That's the code of the model Calendar:
export class Calendar{
public date: string= '';
public type: TypeDate = new TypeDate;
}
export class TypeDate{
public id: number = 0;
public descripcion: String = '';
}
That's the code of my service:
public fetchDates(year: number): Observable<Calendar[]>{
const url = `${this.baseUrl}${year}`;
return this.httpClient.get<Calendar[]>(url);
}
I have tried to extract the data by changing the model:
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 = '';
}
At my component:
fetchHolidays(){
this.calendarService.fetchDates(this.year)
.subscribe((contentCalendar)=>{
console.log(contentCalendar);
console.log(contentCalendar['calendar'][0]['date'])
console.log(contentCalendar.calendar[0].date);
And the error is Cannot read properties of undefined (reading '0')
Console object information
Solution
It looks like I was asking the model what the interface does. I have created an interface just like the last model and I have already been able to access the data. I leave here the example of the interface:
export interface Holidays {
content: Content[];
}
export interface Content {
date: string;
type: Type;
}
export interface Type {
id: number;
description: string;
}
I also leave the example of the request to the service and the console.log:
fetchHolidays(){
this.calendarService.fetchDates(this.year)
.subscribe((holidays)=>{
console.log(holidays.content[1].date);
this.updatedVariables=true;
Answered By - Alejandro Fabra Segarra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.