开发者问题收集

角度订阅推送对象到数组

2018-12-08
39251

我正在制作 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 中,当我们在服务之外调用时,它应该具有填充的数据,而不是像现在这样为空..

还就此制作了一个 工作 stackblitz https://stackblitz.com/edit/angular-q3yphw

请查看具有当前结果的控制台..

console.log("users array", this.users); 中的当前结果 为空数组 []

因此,我 期望 在服务外部和 ngOnInit 内部的 结果 为以下 ,

[
{"id":1,"value":"User One"},
{"id":2,"value":"User Two"},
{"id":3,"value":"User Three"}
]

由于我是 Angular 新手,请帮助我实现预期结果..

3个回答

已分叉您 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.

Result

KShewengger
2018-12-08

您也可以将数据存储在不循环的数组中。

ngOnInit() {

  //Getting the data from json
  this.httpClient.get('https://api.myjson.com/bins/n5p2m').subscribe((response: any) => {      
    this.users.push(...response.data)
    console.log("users array", this.users);  
  })            
}
Sachin Shah
2018-12-08

Angular 可以使用 Promises 和 Observables 来处理异步操作,例如此 http get 请求。关于此概念的信息很多,下面是一个很好的起点: Promise vs Observable

为了进一步阐述,您可以将 http get 请求包装在返回 Observable 的方法中,然后订阅该方法并等待它返回结果,然后再执行日志语句。

Derek
2018-12-08