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.