'foreach through a map that has another map as value in Angular

I made a service in Java that returns as observable a map<k, map<k,v>> and I'm attempting to iterate through the outer map with a foreach. I'm struggling to.

[...]
.then(
    (response: Package) => {
         response.activityMap.forEach((key: string, value: Map<string, number>) => {
             //do something
         });
    }
)
[...]

Package is a type with the following parameters:

export interface Package{ 
    diagnostic?: Diagnostic;
    activityMap?: { [key: string]: { [key: string]: number; }; };
}

What I'm trying to do is to make a forEach that iterates through the "father" map, so for each key //dosomething

But it won't let me use foreach:

This expression is not callable. Type '{ [key: string]: number; }' has no call signatures.



Solution 1:[1]

Since you are returning an observable, you have to first subscribe to the observable, then you can iterate the returned values.

There are 2 approaches in order how we handle subscriptions

Approach 1

Handling subscription inside our component

this.myService.getPackage().subscribe((response: Package) => { 
    response.activityMap.forEach((key: string, value: Map<string, number>) => {
             //do something
         });
})

Also make sure to unsubscribe as well to prevent your application from having memory leaks.

You can do that with TakeUntill RxJS operator https://www.digitalocean.com/community/tutorials/angular-takeuntil-rxjs-unsubscribe

OR

Approach 2

Using Async pipe

Instead of subscribing, you can using async pipes which is considered as a best practice https://blog.angular-university.io/angular-reactive-templates/

Tip

Instead of iterating inside the subscription, I would recommend that you use RxJS Map Operator combined inside a Pipe https://rxjs.dev/api/operators/map

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dimitar Cetelev