比较一下
return this.httpClient.get('https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/suggest', {params: data}).pipe(
map((x: any) => x.suggestions.map((y) => {
return {
...y,
title: y.text
};
})),
);有了这个
return this.httpClient.get('https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/suggest', {params: data}).pipe(
map((x: any) => x.suggestions),
map((y: any) => y.title = y.text)
);为何这些情况不平等?
第一项工作如预期,“移除”建议属性并将属性文本复制为标题。
第二个给我一个值..。非数组
我可以只使用map()函数而不是.map()吗?
发布于 2019-10-03 09:40:15
第一种是RxJS的可管算子映射,第二种是Array的映射函数。
让我们看看您的示例中的类型:
在第一个例子中,您可以观察到对象。在这种情况下,map操作符允许您使用其中的建议数组来转换对象。然后,通过数组的映射函数,将每个项目从x.suggestions数组映射到新项。
const obs$: Observable<{ suggestions: any[] }> = this.httpClient.get('url', { params: data });
obs$.pipe(
map((x: { suggestions: any[] }) => x.suggestions.map((y) => {
return {
...y,
title: y.text
};
})),
);在第二个例子中,在第一个map操作符之后,可以观察到数组。因此,第二映射操作符有一个错误。
const obs$: Observable<{ suggestions: any[] }> = this.httpClient.get('url', { params: data });
const tmp$: Observable<any[]> = obs$.pipe(
map((x: { suggestions: any[] }) => x.suggestions),
);
tmp$.pipe(
map((x: any[]) => x.title = x.text) // this line has error: Property 'title' does not exist on type 'any[]'.
),因为您可以观察到数组,所以您将每个项(从可观察项发出的数组)映射到新项。
如果是Array,则将每个项(从数组中的对象)映射到新项。
您的想法是,在Array中,它允许您将项从数组映射到新项,但事实并非如此。它允许你把整个阵列映射到你想要的任何东西。
作为您想要做的事情的解决方案,请看以下内容:
this.httpClient.get('url', { params: data })
.pipe(
switchMap(x => x.suggestions),
map(x => (...x, title: x.text)),
toArray(),
)现在,通过switchMap,您可以观察到项(而不是数组的可观测性),您可以根据自己的意愿映射每个项,然后通过toArray操作符将其转换为数组的可观测性。
发布于 2019-10-03 04:48:17
在第一个例子中,您使用的是.map()
return this.httpClient.get('https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/suggest', {params: data}).pipe(
map((x: any) => x.suggestions.map((y) => {
return {
...y,
title: y.text
};
})),
);您正在使用suggestions.map()
.map()函数返回和数组。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
看看rxjs中的map()做什么https://www.learnrxjs.io/operators/transformation/map.html
https://stackoverflow.com/questions/58212176
复制相似问题