[英]Angular 7: How to properly this.http.get from a nested response?
I'm doing the Angular 7 tutorial wonder how to properly request a list of items if they are not on the top level, but nested : 我正在做Angular 7教程,想知道如果它们不在顶层而是嵌套的 ,如何正确地请求项目列表 :
Top-Level (works) 顶层(作品)
[
{ id: 123, name: 'Name 123'},
{ id: 124, name: 'Name 124'},
// ...
]
Nested (doesn't work) 嵌套(无效)
{
message: 'x items found.',
data: [
{ id: 123, name: 'Name 123'},
{ id: 124, name: 'Name 124'},
// ...
]
}
Service 服务
// ...
@Injectable({ providedIn: 'root' })
export class ItemService {
private apiUrl = 'api/items'; // items are in .data
constructor(private http: HttpClient) {}
getItems (): Observable<Item[]> {
// Here is the problem:
return this.http.get<Item[]>(this.apiUrl, {
pathToItems: 'data' // <- Pseudocode
});
}
}
Component 零件
// ...
this.itemService.getItems()
.subscribe(items => this.items = items);
I could use subscribe()
in the service and return the content of .data
, but I think there should be a more simple solution. 我可以在服务中使用subscribe()
并返回.data
的内容,但我认为应该有一个更简单的解决方案。 I need to keep the return type (array of Item
). 我需要保留返回类型( Item
数组)。
Any idea? 任何想法?
Thanks in advance! 提前致谢!
You can use RxJs filters like map or filter . 您可以使用map或filter之类的RxJs过滤器 。 That's one of the advantages when using RxJs (Observables). 这是使用RxJ(可观察到的)的优点之一。 You can filter your data before you pass it to your component. 您可以在将数据传递到组件之前对其进行过滤。
An example: 一个例子:
return this.http.get(ITEMS_URL).pipe( filter(response => response.filter(data => data.message === "SUCCEEDED")), map(response => response.map(data => data.items)) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.