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?

4
  • I think the issue is in the other way, why are you using it like a single object when the service is returning you an array of objects? Commented Aug 17, 2020 at 18:01
  • How would you know which hotel you want? Commented Aug 17, 2020 at 18:25
  • cause it will always be single object Commented Aug 17, 2020 at 18:25
  • @PoulKruijt base on number of reservation. I got the same field in my hotels table and users so I am getting only this hotel where reservation number are the same Commented Aug 17, 2020 at 18:26

2 Answers 2

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])
);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.