问题描述
我正在进行有角度的应用程序,并且我有一个空数组,例如
I am making angular application and where i am having an empty array like,
users: any = [];
然后我要在ngOnInit
中进行服务调用,以将数据存储到users
数组中,例如
Then i am making a service call in ngOnInit
to store the data into users
array like,
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);
中的数据,因为该服务调用导致了延迟..
But i am unable to get the data in console.log("users array", this.users);
as because the service call makes a delay..
如何将数据推送到this.users
中,当我们在服务外部调用时,它应该具有已填充的数据,而不是像现在这样为空..
How to push the data into this.users
and when we call outside of the service it should have the filled data and not empty as like now..
还对此进行了有效的堆栈闪电 https://stackblitz.com/edit/angular-q3yphw
请查看具有当前结果的控制台.
Please see the console which has current result..
console.log("users array", this.users);
中的当前结果为空数组 [] .
因此,我期望在服务外部和ngOnInit
内部的console.log("users array", this.users);
中的以下结果,
So i am expecting the following result in console.log("users array", this.users);
outside the service and inside ngOnInit
,
[
{"id":1,"value":"User One"},
{"id":2,"value":"User Two"},
{"id":3,"value":"User Three"}
]
由于我是新手,请帮助我达到预期的结果.
As i am new in angular kindly help me to achieve the expected result..
推荐答案
已经分叉了您 Stackblitz演示
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);
不需要执行.forEach()来存储来自response.data的对象数组,因为Angular已经为您执行了它.因此,每当您将其分配为
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
它将存储您的对象数组[Object, Object, Object]
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.
这篇关于角向数组订阅推送对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!