0

Working on angular4 for a while, today I came to a scenario where my service is returning me a map instead of a JSON response. How can I map that service with my map. Error I am getting in visual studio Type Info cannot be assigned to type Map<string, Info>. My code is as below: Please advice me did I make a correct model class? how to map service map response to my map.

response from service

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

ts file

    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>
    });

Info model

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

service

fetchInfo(): Observable<Info>{
 const url = "/info/getInfo";
 return this.httpClient.get<Info>(url);
}
2
  • Cant you just change your service's return type from <Info> to <Map> ? Commented Aug 9, 2018 at 12:52
  • try this myMap: Info Commented Aug 9, 2018 at 12:55

1 Answer 1

2

The response is still JSON, it's just that the JSON is an object that maps a string to an Info type. So it can defined as { [key: string]: Info }. So your service either needs to defined as:

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

Or if you want a real JavaScript map (not an object), the service needs to explicitly convert the object into a map. The whole thing should look something like this (I didn't have a chance to check the syntax):

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;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.