Home > Blockchain >  Can't go through the array object received from the service but I can see its content
Can't go through the array object received from the service but I can see its content

Time:12-31

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

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);
}

CodePudding user response:

Based on your image, when you are doing this:

.subscribe((dates)=>{....

what you are really doing is this:


.subscribe( (dates: Calendar[])=>{

So, when you are trying to do this.holidays=dates;, holidays should be Calendar[] type as well.

To sum up, dates is something like this array:

[ 
   {  
      date:"01/01/2021",
      type: {
               id: 1,
               description: "Some text like first date or wahtever..."
            }
   },
   {  date:"01/06/2021",
      type: {...}
   },
....
];

So, for instance, if you declare const firstElement = dates[0]; , then firstElement would be:

 {  
      date:"01/01/2021",
      type:  {
               id: 1,
               description: "Some text like first date or wahtever..."
             }
 }

So you can access to field date, doing something like this:

const myFirstDate = dates[0]?.date;

CodePudding user response:

Seems like your dates variable is not an array. It's an object whose property (content property) holds an array. You expect:

dates:Array<Calendar>

What it actually is:

dates: {
  content: Array<Calendar>
}

Simply, you should dates.content.length or dates.content[0], you probably overlooked.

  • Related