简体   繁体   中英

Return Observable of single item from http.get in Angular 5

I have a service that sends requests to an in-memory-web-api. The service includes a method which I want to query (via query string) the API for a single item.

Regardless of specifying a single item in the generic http.get method I am returned an array.

This differs from if a I make a call to the API for a single item using an ID rather than a query when I am returned just the single item.

this.http.get<ITrack>(`api/tracks/1`)
  .subscribe(track => console.log(JSON.stringify(track)));

returns

{"id":1,"artist":"Radiohead","name":"OK Computer","durationSeconds":61,"nominator":null,"playlistPosition":1}

Where as

this.http.get<ITrack>(`api/tracks/?playlistPosition=1`)
  .subscribe(track => console.log(JSON.stringify(track)));

returns

[{"id":1,"artist":"Radiohead","name":"OK Computer","durationSeconds":61,"nominator":null,"playlistPosition":1}]

I can get the second call to return just the item with the following:

this.http.get<ITrack>(`api/tracks/?playlistPosition=1`)
.pipe(
  map(t => t[0])
)
.subscribe(track => console.log(JSON.stringify(track)));

However I can't use methods like single or first as the compiler is expecting a return type of ITrack.

What is the correct way to return a single item here?

So if the endpoint always returns a list, call the get method typed with an ITrack -array.

Simply replace .get<ITrack>(...) with .get<ITrack[]>(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM