以打字稿/角度

时间:2018-08-09 12:43:27

标签: angular typescript

工作了一段时间后,今天我来到了一个场景,其中我的服务正在返回地图而不是JSON响应。如何在我的地图上映射该服务。错误我进入Visual Studio Type Info cannot be assigned to type Map<string, Info>。我的代码如下:请告知我我是否创建了正确的模型类?如何将服务地图响应映射到我的地图。

服务响应

{
"1":{
     "id":"1",
     "name":"Anna"
    },
"2":{
     "id":"2",
     "name":"Martin"
    }
}

ts文件

    myMap: Map<string, Info>;
     this.groupService.fetchInfo().subscribe(data => {
     this.myMap= data; // Error in visual studio: Type Info cannot be 
                       // assigned to type Map<string, Info>
    });

信息模型

// Not sure if this model structure is correct
export interface Info{
  id: string;
  name: string;
}

服务

fetchInfo(): Observable<Info>{
 const url = "/info/getInfo";
 return this.httpClient.get<Info>(url);
}

1 个答案:

答案 0 :(得分:0)

响应仍然是JSON,只是JSON是一个将字符串映射到Info类型的对象。因此可以将其定义为{ [key: string]: Info }。因此,您的服务都需要定义为:

fetchInfo(): Observable<{ [key: string]: Info }>

或者,如果您需要真实的JavaScript映射(而不是对象),则服务需要将对象显式转换为映射。整个过程应该看起来像这样(我没有机会检查语法):

fetchInfo(): Observable<Map<string, Info>> {
    return this.httpClient.get<{ [key: string]: Info }>(url).map(response => { 
        const map = new Map();
        Object.keys(response).forEach(key => {
            map.set(key, response[key]);
        });
        return map;
    });
}
相关问题