Angular calendar async http 'map' of undef

2019-08-01 06:12发布

问题:

I try to install the angular calendar in my app, I have the data of the events in the database, but when I try to call them I get an error:

ERROR TypeError: Cannot read property 'map' of undefined at MapSubscriber.eval

The original code is here: https://mattlewis92.github.io/angular-calendar/#/async-events

My component.ts:

import { Component, ChangeDetectionStrategy, ViewEncapsulation, OnInit } from '@angular/core';
import { ConsultaService } from '../../services/consulta/consulta.service';
import { Consulta } from '../../models/consulta.model';

//calendar imports
import { HttpClient } from '@angular/common/http';
import { CalendarEvent } from 'angular-calendar';
import { map } from 'rxjs/operators/map';
import { Observable } from 'rxjs/Observable';
import {
  /* ... */
} from 'date-fns';

const colors: any = {
  /* ... */
};

@Component({
  selector: 'app-turnos',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './turnos.component.html',
  styleUrls: ['./turnos.component.min.css'],
  encapsulation: ViewEncapsulation.None
})
export class TurnosComponent implements OnInit {

  activeDayIsOpen: boolean = false;
  view: string = 'month';
  viewDate: Date = new Date();

  events$: Observable<Array<CalendarEvent<{ consulta: Consulta }>>>;

  constructor(
    private http: HttpClient,
    public _consultaService: ConsultaService,
  ) {}

  ngOnInit(): void {
    this.fetchEvents();
  }

  fetchEvents(): void {
    const getStart: any = {
      month: startOfMonth,
      week: startOfWeek,
      day: startOfDay
    }[this.view];

    const getEnd: any = {
      month: endOfMonth,
      week: endOfWeek,
      day: endOfDay
    }[this.view];

    this.events$ = this.http
      .get('http://localhost:3000/consulta')
      .pipe(
        map(({ results }: { results: any[] }) => {
          return results.map((consulta: any) => { // <--- error line
            return {
              title: consulta.tratamiento_c,
              start: new Date(consulta.date_a),
              color: colors.yellow,
              meta: {
                consulta
              }
            };
          });
        })
      );
  }

  dayClicked({
    /* ... */
  }

  eventClicked(event: CalendarEvent<{ consulta: Consulta }>): void {
    /* ... */
  }

}

When I use the .get example works well, it shows me all the data. But when I change the url and remove the parameters, by my url http://localhost:3000/consulta it does not work in the same way, the calendar is not rendered and throws the map error and as you can see, the map is included above.

Adding, my consulta.service.ts has this function to bring all the data. How could I subscribe and display the data as the example using my service?

  cargarConsultas() {
    let url = URL_SERVICIOS + '/consulta';

    return this.http.get(url);
  }

I hope you can guide me to the solution. Thanks!

UPDATE

I changed the line

map(({ results }: { results: any[] }) => {

for

map(( results: Consulta[] ) => {

and now I get the data from http, but new error appears:

ERROR TypeError: results.map is not a function

The error continues referring to the line that you mark in the code above

回答1:

Answer for updated question

That's because the json returned by the webservice is no an array of Consulta, but an object which consultats properties is an array. So, in your subscribe, results is not an array

You need to map (using observable's map method) the returned value from the htpp call to an array

cargarConsultas() : Observable<Consulta[]> 
{
   let url = URL_SERVICIOS + '/consulta';
   return this.http.get(url).map(res => res.consultas);
}

Or you can directly access the correct property in the subscribe method

cargarConsultas() {
 let url = URL_SERVICIOS + '/consulta';
 return this.http.get(url);
}

map(( results: any ) => 
{
return results.consultas.map(

Answer for original question

If you declare the map parameter like you originally did, this means that the http call returns an object, with a result property which if an array

 map(({ results }: { results: any[] }) 

From the json you provided, this is not the case. The consultas property contains the array. So it should be:

 map(({ consultas }: { consultas: Consulta[] }) => {
      return consultas.map((consulta: Consulta)  => {
        return {
          title: consulta.tratamiento_c,