0

I got simple service

  getHotels(): Observable<any> {
    return this.http.get(API_URL + '/hotels');
  }

and in my component I got

  getHotels() {
    this.workersService.getHotels().subscribe(
      res => {
        this.hotels = res;
        console.log(this.hotels);
      },
      error => {
        console.log(error);
      }
    );
  }

and output from console.log is

[{…}]
0: {id: 1, id_hotel: "123", client: "test", date: "17.08.2020", team: 1, …}
length: 1
__proto__: Array(0)

And I got acces by for example this.hotels[0].client but I want this.hotels.client How Can I get just object instead of array of objects?

JF.rad
  • 7
  • 4

2 Answers2

0

The specific endpoint you are calling this.http.get(API_URL + '/hotels') is returning an array of objects so unfortunately you will always receive an array, even if there is only one object in it. There is nothing technically wrong with this, this.hotels[0].client is a perfectly normal/acceptable way to handle an endpoint which returns a list of one item.

That said if you must have a single object returned, the endpoint itself needs to be informed to return one object in some way.

If you are calling a public API, check the documentation to see whether:

  • there is a more specific endpoint to be calling (e.g. this.http.get(API_URL + '/hotels/' + hotelId), where hotelId contains the ID of a specific hotel
  • whether the endpoint supports custom headers (e.g. this.http.get(API_URL + '/hotels', headers), where headers is a headers object (see this answer for more)

If you instead own the API, you would need to implement one of the methods above first and then use it in the same way.

nate-kumar
  • 1,675
  • 2
  • 8
  • 15
0

Your method is called getHotels(), your URL ends with /hotels, this all implies the server returns an array. You should either change your server, or map the response to the first item:

this.workersService.getHotels().pipe(
  map((hotels) => hotels[0])
);
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149