Angular: Material Table Convert API Array For Material Table

I am trying to retrieve an array of json data from an API and present it as a material table. However am facing problems, it reads that the attributes cannot be found.

How can I solve this?

lead.service.ts

  getAllLeads(): Observable<any> {
    return this.http.get(this.base_url, {
      headers: this.httpHeaders
    });
  }

leadtable.component.ts

export class Lead {
    business_id: Business [];
    genre_id: Genre [];
    language_id: Language [];
    activity: string;
    phone_no: number;
    event_title: string;
    name: string;
    email: string;
    city: string;
    org_name: string;
    partner_type: string;
    college_activity: string;
    college_music_contest: string;
    college_name: string;
    budget: string;
    prize: string;
    other: string;
    gig_type: string;
    date_of_event: Date;
    event_city: string;
}

  ngOnInit(): void {
   this.getLeads()
    console.log(this.dataSource); //undefined
    this.displayedColumns = ['name', 'partner_type', 'city'];
  }

  getLeads = () => {
    this.leadApi.getAllLeads().subscribe(
      data => {
        this.lead_list = data;
        console.log(this.lead_list);
      },
      error => {
        console.log(error);
      }
    )
  }

1 answer

  • answered 2020-12-01 21:36 Becike

    Can you share your html code too? Angular's Material table sometimes can be tricky.

    Your console.log(this.datasource) is undefined because of the async call.

    Try to use MatTableDataSource, you can pass in observables too, and it will be easier to use for example paginator, or sorter later.