0

I'm struggling with the ES6 Map Datatype in my HTTP-Service.

In my Service I return an Observable, containing a Map:

  getLayout(dims: Map<number, [number, number]>, rels: [number, number][]): Observable<Map<number, [number, number]>> {
    // ES6 Map can not be json-stringified
    let jsonDims: { [x: number]: [number, number]; } = {}
    dims.forEach((dim, gid) => {
      jsonDims[gid] = dim
    });
    const data = { "dims": jsonDims, "rels": rels }

    return this.http.post<Map<number, [number, number]>>(
      environment.backend_url + '/layout',
      JSON.stringify(data),
      this.options
    ).pipe(catchError(err => {
        console.error(err.message)
        return throwError("Error occurred while requesting layout.")
    }));
  }

However, when I try to process the response-data in my component:

this.layoutService.getLayout(dims, rels).subscribe(layout => {
  console.log(layout); // works: I see the data, structured correctly

  for (const [gid, pos] of layout) { // fails
    console.log(gid)
    console.log(pos)
  }
});

I get error messages like:

layout not iterable

layout has no attribute 'get'

So it seems layout is not a valid Map, so how would I have http.post<Map<number, [number, number]>>() actually return a Map-object over which I can iterate or use get()?

TehQuila
  • 628
  • 1
  • 8
  • 19
  • 2
    You're never going to get an instance of a Map back from an HTTP service call. You're going to get JSON, XML, text, etc., nor can you POST a Map instance. You would need to convert your Map to an Object and vice versa when you receive the response. – Brandon Taylor Oct 15 '21 at 16:12
  • Thanks @Brandon that makes sense! How would I go about converting my HTTP data to and from a Map object? Would I do that in my component? Is that where the .map() function comes into play? – TehQuila Oct 16 '21 at 10:52
  • I would make the conversion a separate function in the service. – Brandon Taylor Oct 16 '21 at 13:14

0 Answers0