【发布时间】:2019-05-09 20:06:48
【问题描述】:
我正在制作角度应用程序,并且我有一个空数组,例如,
users: any = [];
然后我在ngOnInit 中进行服务调用以将数据存储到users 数组中,例如,
ngOnInit() {
//Getting the data from json
this.httpClient.get('https://api.myjson.com/bins/n5p2m').subscribe((response: any) => {
console.log("response", response.data);
response.data.forEach(element => {
//Pusing the data to users array
this.users.push(element);
});
})
//Trying to get the complete array after push of the element from the service response data
console.log("users array", this.users);
//But it shows empty array
}
但我无法获取console.log("users array", this.users); 中的数据,因为服务调用延迟了..
如何将数据推送到this.users,当我们在服务外部调用时,它应该有填充的数据,而不是像现在这样为空..
还针对它进行了工作堆栈闪电战 https://stackblitz.com/edit/angular-q3yphw
请查看具有当前结果的控制台..
console.log("users array", this.users); 中的当前结果是空数组[]。
所以我期待在console.log("users array", this.users);服务外和ngOnInit内出现以下结果,
[
{"id":1,"value":"User One"},
{"id":2,"value":"User Two"},
{"id":3,"value":"User Three"}
]
由于我是 Angular 新手,请帮助我达到预期的结果..
【问题讨论】:
标签: javascript arrays angular typescript angular6