0

A project entity has the following field(java):

Map<String, String> employeeEmailToLoggedTimeMap = new HashMap<>();

I serialize the project with JSON and send it to my Angular frontend. The Map gets transformed into this form:

"employeeEmailToLoggedTimeMap":{ 
   "someEmail123123@email.com":"23",
   "someEmail123132423@email.com":"123",
   "someEmail1232341123@email.com":"12",
   "someEmail123123123@email.com":"23"
}

In Angular, i defined the field of the object im trying to receive the following way:

employeeEmailToLoggedTimeMap?: Map<string, string>;

When i do a GET-request to receive all projects

  getProjects(): Observable<Project[]> {
    return this.http.get<Project[]>(BASE_URL, this.authService.setHeaders('application/json'))
      .pipe(
        catchError(this.handleService.error.bind(this))
      )
  }

the empoyeeEmailToLoggedTimeMap data isn´t transformed to a map. I receive the data without errors, but none of the map operators work.

For example, if i did

getProjects(): Observable<Project[]> {
    return this.http.get<Project[]>(BASE_URL, this.authService.setHeaders('application/json'))
      .pipe(
        tap(projects => projects.forEach(project => {
          console.log(project.employeeEmailToLoggedTimeMap);
          console.log(project.employeeEmailToLoggedTimeMap.size);
        })),
        catchError(this.handleService.error.bind(this))
      )
  }

it would log all the data saved in project.employeeToLoggedTimeMap, but project.employeeEmailToLoggedTimeMap.size would return undefined and all other map operators don´t work too. So it seems like it does not recognize and transform the data into the map. So, how would i transform the data i get into the map i want?

M.Dietz
  • 900
  • 10
  • 29

2 Answers2

4

This answer may be what you are looking for. Typescript doesn't convert things for you, it trusts when you specify types even if the thing you receive from server is not what it expects it will pretend that it is.

1

that is because when you get it from the server it will be as a JSON object so your HashMap will actually be something like a class/interface; What you need to do is convert the object to a Map, to do this i suggest you create a constructor for Project like so:

export class Porject {
  employeeEmailToLoggedTimeMap: Map<string, int>;
  property1: string;
  property2: string;
  ..other properties
  
  constructor(item: any) {
    this.employeeEmailToLoggedTimeMap = new Map(Object.entries(item.employeeEmailToLoggedTimeMap));
    this.property1 = item.property1;
    this.property2 = item.property2;
  }
}

then you can simply:

 return this.http.get<Project[]>(BASE_URL, this.authService.setHeaders('application/json'))
      .pipe(
        map(projects => projects.map(x => new Project(x)),
        catchError(this.handleService.error.bind(this))
      )
Chirag Patel
  • 364
  • 2
  • 12