我正在制作角度应用程序,并且我有一个空数组,例如,
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 https://stackblitz.com/edit/angular-q3yphw
请查看具有当前结果的控制台。
目前结果 in console.log("users array", this.users);
是空数组[].
So i am 期待下列result in console.log("users array", this.users);
服务外和服务内ngOnInit
,
[
{"id":1,"value":"User One"},
{"id":2,"value":"User Two"},
{"id":3,"value":"User Three"}
]
由于我是角度新手,请帮助我实现预期结果。