Is there a way to effectively transmit an observable array containing instances of Map<number, Employee> using the async pipe mechanism?

This is my Interface and Type Definition

export interface EmployeeDetails {
  id: number;
  name: string;
}
export type EmployeesDirectory = Map<number, EmployeeDetails>;

This is my Service Implementation

class EmployeeServiceManager {
  employeesData$: Observable<EmployeeDetails[]> = of([
    {
      id: 1,
      name: 'John',
    },
    {
      id: 2,
      name: 'Mary',
    },
  ]);
  employeesDataMap$: Observable<EmployeesDirectory> = this.employeesData$.pipe(
    map((employees) => {
      const directory: [number, EmployeeDetails][] = employees.map((employee) => [
        employee.id,
        employee,
      ]);
      const employeeDirectory: EmployeesDirectory = new Map(directory);
      return employeeDirectory;
    })
  );
}

This is the Child Component Configuration

@Component({
  selector: 'app-child',
  encapsulation: ViewEncapsulation.ShadowDom,
  imports: [CommonModule],
  template: `{{employees | json}}<br>{{employeesMap | json}}`,
})
export class ChildContent {
  @Input() employees: EmployeeDetails[] = [];
  @Input() employeesMap: EmployeesDirectory = new Map();
}

This is the Parent Component Setup

@Component({
  selector: 'my-app',
  shadowDom: true,
  imports: [CommonModule, ChildContent],
  template: `
    <h1>Greetings from Angular!</h1>
    <app-child 
      <!-- This section works fine -->
      [employees]="(employees$ | async) ?? []" 
      <!-- This part generates an error -->
      [employeesMap]="(employeesDataMap$ | async) ?? {}"
    />
  `,
})

Stackblitz Link: https://stackblitz.com/edit/stackblitz-starters-mhjnga?file=src%2Fmain.ts

The following error message is encountered: Type 'EmployeesDirectory | {}' cannot be used as 'EmployeesDirectory' Type '{}' lacks properties present in type 'Map<number, EmployeeDetails>': clear, delete, forEach, get, plus 8 more.

Your assistance is greatly appreciated

Answer №1

If you want to display the values of a map, make sure to use the keys or values iterators. Update the template in your child component with something like:

template: `employees: {{employees | json}}<br>employeesMap: <div *ngFor="let key of employeesMap?.keys()">{{ key }}, {{ employeesMap?.get(key)?.name }}</div>`

Also, be sure to include this in the class:

@Input() employeesMap: EmployeesMap | null = new Map();

In the parent component:

<app-child 
      [employees]="(employees$ | async) ?? []" 
      [employeesMap]="employeesMap$ | async"
    />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The use of Next.js v12 middleware is incompatible with both node-fetch and axios

I am facing an issue while developing a middleware that fetches user data from an external endpoint using Axios. Surprisingly, Axios is not functioning properly within the middleware. Below is the error message I encountered when using node-fetch: Module b ...

Is there a way to create identical copies of data with the identical names?

Here is the code I have written: this.temp1.push(this.json); for(let i=0; i<this.temp1.length; i++){ if(this.temp1[i].name == this.json.name){ this.orderList[i] = this.json; this.DBorder[i] = this.order_json; } ...

Display or conceal an icon based on the data in the field

Can someone provide guidance on how to make an icon appear or disappear based on the logic within [ngIf]? The icon should only be displayed if there is information in a specific field. Should I implement this inside ngIF or in my TS file? Can the icon cl ...

Storing selected items from a tree table into an array

Currently, I am developing an Angular application and incorporating the PrimeNG tree table component. Below is my code snippet: <p-treeTable [value]="files5" [columns]="cols" selectionMode="checkbox" [(selection)]=& ...

Issue encountered with Angular 13 and Twilio Sync: The variable name is not recognized as a constructor, resulting in

After upgrading to angular 13, I encountered a problem that was not present when using angular 10. In my TwilioSyncService, the require statement is included in the constructor because it is an Injectable service requirement. The code snippet shows how t ...

Angular studyTime must be before grantTime for validation 2 date

I need to validate 2 dates using mat-datepicker in my Angular application. Here is the code snippet for the HTML file: <mat-form-field class="w-100-p"> <input matInput [matDatepicker]="st" formControlName="stu ...

Guide on removing a key from an object in TypeScript

My variable myMap: { [key: string]: string[] } = {} contains data that I need to modify. Specifically, I am trying to remove a specific value associated with a certain key from the myMap. In this case, my goal is to delete value1 from myMap[Key1]. Despit ...

What is the definition of a non-arrow React functional component in TypeScript?

Defining types for a React functional component in TypeScript can be done like this: export const Component: React.FC = () => { return // Content }; But how would you define the types for a non-arrow function? function Component() { return // Con ...

Discovering ways to retrieve the complete HTTP response in Angular to access certain response headers

In my angular app, I need to check for specific response headers to handle JWT validation. If a user tries to access a route that requires a valid JWT with an expired token, the back-end ASP.NET Core server will have a response header token-expired: true. ...

Error: Angular 6 and karma have encountered a problem - "Unable to load "@angular-devkit/build-angular", as it is not recognized."

Upon upgrading to the latest version of Angular, my karma tests ceased functioning and started crashing with this error log: 14 04 2018 14:17:00.453:ERROR [preprocess]: Can not load "@angular-devkit/build-angular", it is not registered! Perhaps you ar ...

struggling to access the value of [(ngModel)] within Angular 6 component

When working in an HTML file, I am using ngModel to retrieve a value that I want to utilize in my component. edit-customer.component.html <input id="userInfoEmail" type="text" class="form-control" value="{{userInfo.email}}" [(ngModel)]="userInfo.email ...

Leveraging Amazon IVS Player within Angular

Struggling to integrate the npm version of the amazon-ivs-player with Angular, as it seems optimized for webpack while I am using angular-cli. Following a guide at this link. The issue arises with importing the wasm files in my Angular application: ERROR ...

Learn how to break down Angular 2 with Typescript in just 5 minutes by troubleshooting issues

I've been delving into the world of TypeScript and Angular 2 by following the guide at https://angular.io/guide/quickstart. After going through all the steps, I encountered some errors with the final step npm start. Here's what I got: Microsoft ...

How can an additional value be sent to the form validation method?

I have created a form group like this: import { checkPasswordStrength } from './validators'; @Component({ .... export class PasswordComponent { ... this.userFormPassword = this.fb.group({ 'password': ['', [ ...

Does Angular 8 development mode implement tree-shaking?

I am curious to know if tree-shaking occurs during Angular 8 development mode. When running the following command: ng build I understand that tree-shaking happens when I use the command below: ng build --optimization=true|false ...

The sanitizer variable becomes null when accessed outside of the NgOnInit function in Angular using TypeScript

At first, I added DomSanitizer to the component: import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser'; Next, a class was created and included in the constructor: export class BlocklyComponent implements OnInit { primar ...

How to include an image in a file type using Angular 2 and TypeScript

Is it possible to assign an image to a file type variable in Angular 2? I attempted the following approach: private file:File; setImage(){ this.file = "../assets/image/image.jpg" } Unfortunately, this method did not succeed. ...

What NonNullable<T> Means in TypeScript

During my search for a Nullable type in TypeScript, I stumbled upon the NonNullable type in the file path: C:\Program Files\Microsoft VS Code\resources\app\extensions\node_modules\typescript\lib\lib.es6.d.ts T ...

Intellisense fails to function properly after attempting to import a custom npm package

I've encountered an issue with a custom npm package that I created using storybook. The components function properly in other projects when imported, but the intellisense feature is not working as expected. Interestingly, when I import the same compon ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...