简体   繁体   English

从Angular 5中的http.get返回单个项目的Observable

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

I have a service that sends requests to an in-memory-web-api. 我有一项将请求发送到内存Web API的服务。 The service includes a method which I want to query (via query string) the API for a single item. 该服务包括一个我想查询(通过查询字符串)单个项目的API的方法。

Regardless of specifying a single item in the generic http.get method I am returned an array. 无论在通用的http.get方法中指定单个项目,我都会返回一个数组。

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. 这与我仅返回单个项目时使用ID而不是查询使用单个项目的API调用API的情况不同。

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. 但是,我不能使用诸如single或first之类的方法,因为编译器希望返回的是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. 因此,如果端点始终返回列表,请调用以ITrack键入的get方法。

Simply replace .get<ITrack>(...) with .get<ITrack[]>(...) . 只需将.get<ITrack>(...)替换为.get<ITrack[]>(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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