-1

I am injecting making a basic http request to a online api (randomuser.me), and I want to create an array of 3 objects with the result. I'm trying to subscribe to the observable and create local variables that holds the name and last name of each person object. But, I can't push this objects to a root level property I declared first, as it says, "can't push to undefined. I'm using Angular 12

this is the .ts code:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-beneficiario-card',
  templateUrl: './beneficiario-card.component.html',
  styleUrls: ['./beneficiario-card.component.scss'],
})
export class BeneficiarioCardComponent implements OnInit {
  @Output() usuariosEmitter = new EventEmitter<any[]>();

  public beneficiarios: any[];
  private benerficiariosUrl = 'https://randomuser.me/api/?results=1';

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get(`${this.benerficiariosUrl}`).subscribe((data: any) => {
      const name = data.results.map(
        (usuario: string) => usuario['name']['first']
      );
      const last = data.results.map(
        (usuario: string) => usuario['name']['last']
      );
      const beneficiario: Beneficiarios = { name: name[0], last: last[0] };
      this.beneficiarios.push(beneficiario);
    });
  }
}

export interface Beneficiarios {
  name: string;
  last: string;
}

Thanks in advance.

Julio Rodriguez
  • 499
  • 6
  • 16

1 Answers1

2

You have only declared the array and not initialized it. try doing this

public beneficiarios: any[] =[];

this should sort it out.

R.christie
  • 86
  • 2
  • 1
    Rather than having any as the type, since you have declared a type interface its best if you declare the array as public beneficiarios: Beneficiarios[]=[]; This would make sure that the array is type safe. – R.christie Jan 31 '22 at 03:00