我正在制作 Angular 应用程序,并且我有一个空数组,例如,
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
当我们在服务外部调用时,它应该具有填充的数据,而不是像现在一样为空..
还针对它做了一个工作堆栈 Blitz 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 新手,请帮助我实现预期结果..
最佳答案
fork 了你 Stackblitz Demo
If you want to manipulate your data after the HTTP Client response, you can actually do so by playing with the RxJS operators. After those methods inside the pipe, when you subscribe to its final value, it will directly render to your template.
this.httpClient
.get('https://api.myjson.com/bins/n5p2m')
.pipe(
map(response => response.data),
tap(users => console.log("users array", users)) // users array [Object, Object, Object]
)
.subscribe(users => this.users = users);
If you don't want to use the RxJS Operators, you can still manipulate it after you had subscribed to its final value and perform your manual data manipulation
There's no need to perform the .forEach() to store the array of objects from your response.data as Angular had already perform it for you. So whenever you assign it as
this.users = response.data
it will store your Array of Objects[Object, Object, Object]
this.httpClient
.get('https://api.myjson.com/bins/n5p2m')
.subscribe(response => this.users = response.data); // This will directly store your response data in an array of objects.
关于javascript - Angular 订阅将对象推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53680000/