json Angular - HttpClient:将 Get 方法对象结果映射到数组属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46700055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular - HttpClient: Map Get method object result to array property
提问by Netwobble
I am calling an API that returns a JSON Object. I need just the value of the array to map to a Observable . If I call api that just returns the array my service call works.
我正在调用一个返回 JSON 对象的 API。我只需要将数组的值映射到 Observable 。如果我调用只返回数组的 api,我的服务调用就可以工作。
Below is my sample code ..
下面是我的示例代码..
// my service call ..
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Show} from '../models/show';
import {HttpClient} from '@angular/common/http';
@Injectable()
export class MyService {
constructor(private http: HttpClient ) { }
findAllShows(): Observable<Show[]> {
return this.http
.get<Show[]>(`${someURL}/shows`)
}
}
If the return is a JSON Object such as below this fails..
如果返回是一个 JSON 对象,如下所示,这将失败..
// Service API that FAILS ...
{
"shows": [
{
"id": "123f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-13 15:54:47",
"name": "Main Show1"
},
{
"id": "456f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-14 15:54:47",
"name": "Main Show2"
},
{
"id": "789f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-17 15:54:47",
"name": "Main Show3"
}
]
}
Now this one works if I just return the Array
现在,如果我只返回数组,这个就可以工作了
// Service API that Works ...
[
{
"id": "123f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-13 15:54:47",
"name": "Main Show1"
},
{
"id": "456f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-14 15:54:47",
"name": "Main Show2"
},
{
"id": "789f9165-80a2-41d8-997a-aecc0bfb2e22",
"modified": "2017-08-17 15:54:47",
"name": "Main Show3"
}
]
How do I map the JSON object Observable into an Array Observable???
如何将 JSON 对象 Observable 映射到数组 Observable ???
回答by CozyAzure
You can simply .map()your http call, which is an Observable, to return the data type that you want.
您可以简单地使用.map()http 调用(即 )Observable来返回所需的数据类型。
findAllShows(): Observable<Show[]> {
return this.http
.get(`${someURL}/shows`)
.map(result=>result.shows)
}
Your httpClient.get()should return an Observable, which you have explicitly stated it thought Observable<Show[]>. You .map()is an operator that transform the observable into a new one.
您httpClient.get()应该返回一个Observable,您已经明确表示它认为Observable<Show[]>。你.map()是一名将可观察对象转换为新对象的操作员。
More on .map()operator: http://reactivex.io/documentation/operators/map.html
更多关于.map()运营商:http: //reactivex.io/documentation/operators/map.html
Update:
更新:
For RXJS version 6 and above, simply use .pipe()to pipe the .map()operator:
对于 RXJS 版本 6 及更高版本,只需使用.pipe()管道.map()操作符:
findAllShows(): Observable<Show[]> {
return this.http
.get(`${someURL}/shows`)
.pipe(map(result=>result.shows))
}
回答by MajidJafari
Latest HttpClientwhich should be used instead of httphas no mapmethod. You should first import it by import { map } from 'rxjs/operators';Then you should use it this way:
HttpClient应该使用的最新版本,而不是http没有map方法。你应该先导入它import { map } from 'rxjs/operators';然后你应该这样使用它:
this.http.get(`${someURL}/shows`).pipe(
map(res => res['shows'])
)
回答by Sreejith sreeji
.map(res=> res['shows'] )does the trick
.map(res=> res['shows'] )有诀窍
回答by Netwobble
Thanks All, I was able to find solution by combining responses from @ Arun Redhu by providing a transfer object interface that the server sends back. Then solution provided by @CozyAzure by using the .map() to transform one Observable to the correct Observable Show[].
谢谢大家,通过提供服务器发回的传输对象接口,我能够通过组合来自@Arun Redhu 的响应来找到解决方案。然后由@CozyAzure 提供的解决方案通过使用 .map() 将一个 Observable 转换为正确的 Observable Show[]。
Full Solution below for those interested.
下面的完整解决方案供感兴趣的人使用。
import {Observable} from 'rxjs/Observable';
import {Contact} from '../models/show';
import {environment} from '../../../environments/environment';
// Use the new improved HttpClient over the Http
// import {Http, Response} from '@angular/http';
import {HttpClient} from '@angular/common/http';
// Create a new transfer object to get data from server
interface ServerData {
shows: Show[];
}
@Injectable()
export class ShowsService {
constructor(private http: HttpClient ) { }
// want Observable of Show[]
findAllShows(): Observable<Show[]> {
// Request as transfer object <ServerData>
return this.http
.get<ServerData>(`${apiURL}/shows`)
// Map to the proper Observable I need
.map(res => <Show[]>res.shows);
}
}
All great now!!! Thanks . So depending on data returned I can either use directly or map to proper Observable I need.
现在一切都好!!!谢谢 。因此,根据返回的数据,我可以直接使用或映射到我需要的适当 Observable。
回答by Arun Redhu
There are 2 approaches of doing this. You can use .mapoperator form the observable to map one type of observable into another and second approach includes just with the help of interface.
有两种方法可以做到这一点。您可以使用.map可观察对象的运算符将一种类型的可观察对象映射到另一种类型,而第二种方法仅在界面的帮助下包括在内。
1st Approaches (with the help of .map)
第一种方法(在 的帮助下.map)
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
interface ItemsResponseObj {
id: string,
modified: string,
name: string
}
interface ItemsResponse {
shows: Array<ItemsResponseObj>;
}
@Injectable()
export class AppService {
constructor(private http: HttpClient) { }
getData(): Observable<ItemsResponseObj[]> {
return this.http.get<ItemsResponse>('api/api-data.json')
.map(res => res.shows);
}
}
and in the 2nd approach with the help of wrapping interfaces
并在第二种方法的帮助下包装接口
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
interface ItemsResponseObj {
id: string,
modified: string,
name: string
}
interface ItemsResponse {
shows: Array<ItemsResponseObj>;
}
@Injectable()
export class AppService {
constructor(private http: HttpClient) { }
getData(): Observable<ItemsResponse> {
return this.http.get<ItemsResponse>('api/api-data.json')
}
}

