Angular HTTP客户端GeoServer REST API映射



我正在使用一个Angular服务来与GeoServer REST API交互。获取层的JSON响应为:

{
"layers": {
"layer": [
{
"name": "facility",
"href": "http://localhost/geoserver/rest/workspaces/unacorn/layers/facility.json"
},
{
"name": "opensky",
"href": "http://localhost/geoserver/rest/workspaces/unacorn/layers/opensky.json"
}
]
}
}

我的服务方法是:

public getLayers(): Observable<Layer[]> {
let layerUrl = this.geoUrl + "/rest/workspaces/unacorn/layers";

return this.http.get<Layer[]>(layerUrl, this.httpOptions)
.pipe(
map(response => {
return {
layers: <Layer[]>response.layers.layer
}
})
)
}

* * *更新7/7:呼叫方代码为:

ngOnInit() {
let layers = Layer[];

this.geoService.getLayers().subscribe((response: Layer[]) => {
if (response) {
console.log(response.length) // Array length 2
layers = response;
}
});
console.log(layers.length) // Array length 0

在控制台中,第二日志输出显示了第一,这似乎意味着它被执行之前,订阅了。我可以用范围来解决这个问题,但我似乎错过了一些基本的东西。

END OF UPDATE

一个层的模型是:

export interface Layer {
name: string
href: string
}

数据正确返回,但我无法使映射到我的模型正常工作。这是我在编译时看到的错误:

Type 'Observable<{data: any;}>'不能赋值给类型'Observable<Layer[]>'。键入"{data: any;}'缺少类型'Layer[]'的以下属性:length,pop, push, concat, and more.ts(2322)

我读过的所有文档和帖子都表明,向模型接口投射是正确的方法。我可能只是漏掉了一些简单的东西。TIA有任何帮助!

错误在于:

return this.http.get<Layer[]>(layerUrl, this.httpOptions)

你在写GET的返回类型应该是Layer[],但它不是。它是一个具有图层属性的对象。GET (<>中的值)的类型应该是API返回的类型。要解决这个问题,可以创建一个表示返回值类型的接口。解决方案:

export interface ApiResponse {
layers: {
layer: Layer[]
}
}
public getLayers(): Observable<Layer[]> {
let layerUrl = this.geoUrl + "/rest/workspaces/unacorn/layers"; 
return this.http.get<ApiResponse>(layerUrl, this.httpOptions)
.pipe(
map(response => {
return response.layers.layer;
})
)
}

最新更新