Oskar Mikael
Oskar Mikael

Reputation: 326

Angular GET requests returns Object instead of Array of Objects

My GET request returns the data from my API as Objects inside an Object, and not an Array of Objects. This denies me from printing the data, since you need an iterable.

I don't really understand why this specific requests' output is different, since I have other GET requests that works just fine.

The component

this.apiService.getList(this.listId).subscribe((results: any) => {
      this.recipes = results
      console.log(results)
    })

The service

getList(listId) {
    return this.http.get(`https://secure-fortress-48055.herokuapp.com/api/v1/lists/${listId}`).pipe(
      map((res: any) => res)
    )
  }

The output looks like this enter image description here

I'm thinking the mapping does nothing right now, since the response doesn't have any type set to it, so perhaps something is wrong with my API?

The data is fetched from my Laravel API, that uses a Resource

  public function toArray($request)
    {
        return [
            'id' => (string)$this->id,
            'type' => 'Recipes',
            'attributes' => [
                'name' => $this->name,
                'meal_id' => $this->meal_id,
                'list_id' => $this->list_id,
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ]
        ];
    }

Any idea what the issue is?

Upvotes: 1

Views: 2235

Answers (1)

sofa_maniac
sofa_maniac

Reputation: 1647

In the Angular code, you can map the key-value pairs to an array of the values.

Object.values(res)

So, the pipe part of the service code will be:

pipe(map((res: any) => Object.values(res)))

This will return an array with the values of that key-value pair collection.

Note: This is an Angular-specific solution.

Upvotes: 2

Related Questions