Angular 订阅将对象推送到数组

Man*_*gan 3 javascript arrays typescript angular angular6

我正在制作角度应用程序,并且我有一个空数组,例如,

  users: any = [];
Run Code Online (Sandbox Code Playgroud)

然后我进行服务调用以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
  }
Run Code Online (Sandbox Code Playgroud)

但我无法获取数据,console.log("users array", this.users);因为服务呼叫造成了延迟。

如何将数据推送到this.users服务中,当我们在服务外部调用时,它应该具有填充的数据,而不是像现在这样为空。

还做了一个关于它的工作 stackblitz 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"}
]
Run Code Online (Sandbox Code Playgroud)

由于我是角度新手,请帮助我实现预期结果。

KSh*_*ger 6

已经分叉了你的Stackblitz Demo

如果您想在 HTTP 客户端响应后操作数据,实际上可以通过使用 RxJS 运算符来实现。在管道内的这些方法之后,当您订阅其最终值时,它将直接渲染到您的模板。

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);
Run Code Online (Sandbox Code Playgroud)

如果您不想使用 RxJS 运算符,您仍然可以在订阅其最终值并执行手动数据操作后对其进行操作

无需执行 .forEach() 来存储 response.data 中的对象数组,因为 Angular 已经为您执行了该操作。所以每当你将它分配为

this.users = response.data它将存储您的对象数组[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.
Run Code Online (Sandbox Code Playgroud)

结果