Angular subscribe push object to array

后端 未结 3 1181
伪装坚强ぢ
伪装坚强ぢ 2021-01-07 00:17

I am making angular application and where i am having an empty array like,

  users: any = [];

Then i am making a service call in ngOn

3条回答
  •  伪装坚强ぢ
    2021-01-07 00:54

    Had forked you 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.
    

提交回复
热议问题