[英]Why can't I access a global property inside the ngOnInit Method?
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.我正在向在线 api (randomuser.me) 注入一个基本的 http 请求,我想用结果创建一个包含 3 个对象的数组。 I'm trying to subscribe to the observable and create local variables that holds the name and last name of each person object.
我正在尝试订阅 observable 并创建包含每个人 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
但是,我不能将此对象推送到我首先声明的根级别属性,正如它所说,“不能推送到未定义。我正在使用 Angular 12
this is the.ts code:这是.ts代码:
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.提前致谢。
You have only declared the array and not initialized it.您只声明了数组并没有对其进行初始化。 try doing this
尝试这样做
public beneficiarios: any[] =[];
this should sort it out.这应该解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.