javascript - Angular 订阅将对象推送到数组

标签 javascript arrays angular typescript angular6

我正在制作 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.

Result

关于javascript - Angular 订阅将对象推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53680000/

相关文章:

JavaScript 函数和 new 运算符

清除一个字符数组 c

php - 将大型数组转换为无循环的关联数组

javascript - ASP.NET Core - 运行多个 Angular 2 应用程序

javascript - 如何从一个指定的子元素中获取 innerHTML

javascript - 如何获取客户端用户的最后一条消息?

javascript - 如何使用 "Scroll To"来考虑不同媒体查询的固定导航高度?

javascript - 创建特定对象并从 SerializeArray 获取值的 Node.js 函数

css - 使用 flex-layout 设置宽度导致左侧在没有滚动的情况下被切断

angular - 如何在 DevTools 中检查垃圾 Observables?