Angular AOT and Typescript mapping tutorial

I have encountered a problem with using TypeScript map in my Angular application. When I run the application using 'ng serve', everything works fine. However, if I use 'ng serve --aot', the maps are not functioning as expected. Despite not receiving any exceptions, the maps appear to be null during debugging. I would like to know if this is a known issue and if there is a workaround available. Thank you for your assistance.

//myLibrary

export class MyModule {
   static forRoot(config: MyConfig ): ModuleWithProviders {
    return {
      ngModule: MyModule,
      providers: [
          {provide: MY_CONFIG, useValue: config} 
      ]
    }
  }

}


export class MyConfig {
    myArray? :  string[];
    myMap?: Map<string, string[]>;

}

//user application

export const testMap: Map<string, string[]> = new Map<string, string[]>();
testMap.set("key1", ["value1", "value2"]);
testMap.set("key2", ["value3", "value4"]);


@NgModule({
  declarations: [
// some code
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    HttpClientModule,
    MyModule.forRoot({
        myArray: ["1234"],
        myMap: testMap,
      }
    ),
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule {

}

Answer №1

One issue arises when using @NgModule because only statically analyzable elements can be used for building with --aot. This means that neither functions inside @NgModule nor in the static forRoot method are allowed.
To create a Map, functions such as ctor and set must be called, which is not permitted. However, replacing Map with ordinary arrays will solve this problem.
Later, a Map can be constructed from an array, like so:

//...
export class MyConfig {
    myArray? :  string[];
    myMap?: [string, string[]][];
}
//...
export const testMap = [['test1', ['test1', 'test2']]]
//...
// setting up imports
MyModule.forRoot({
    myArray: ["1234"],
    myMap: testMap,
  }
),
//...
// config usage in your library
@Injectable()
export SomeService {
  private readonly myMap: Map<string, string[]>;
  constructor(@Inject(MY_CONFIG) config: MyConfig) {
    // converting from array to map
    this.myMap = new Map(config.myMap);
  }
}

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

TypeScript Algorithm for Expressions

I have a list of logical expressions, const expressions = [ 'A&(B|C)', 'A|(B&C)', 'A|(B&(C|D))', 'A|(B&C&D)', ]; From these expressions, I am aiming to obtain the following output ...

Algorithm for organizing pagination to ensure consistent page sizes and prevent excessively large or small pages

My goal is to create a pagination algorithm that distributes elements evenly per page, with specified minimum and maximum thresholds. I aim to maximize the number of elements per page while adhering to the minimum rule. I've attempted to develop my o ...

ngx-slider dynamic positioning of the ceiling value

https://i.sstatic.net/aLBtd.png I am currently facing an issue with maintaining consistent placement of the 'infinity sign' across different screens. It appears that the offset is determined within the slider component code. The icon's posi ...

Subscribe again to an observable from a header module

Within my Angular service, I have an Observable that showcases a countdown timer for a user's e-commerce order when they reach a specific route after adding items to their cart. Although it functions correctly the first time an order is initiated, if ...

Issue with noUnusedLocals flag detection within function* block

Compiler options: "noUnusedLocals": true, "noUnusedParameters": true, are not functioning properly within functions. An error is encountered in the following example: export class AllReduxSagas { [ts] Property 'someService' is declared bu ...

Having trouble with typecasting in Angular 9 after receiving an HTTP response?

When initializing my component, it fetches student information from an API. Here is the ngOnInit code for component-version1: ngOnInit(): void { if(!this.student) { this.studentsService.getStudentDetail(this.id).subscribe( (response: Stu ...

Is there a way to modify the style when a different rarity is selected in Next.JS?

Is there a way to change the style depending on the rarity selected? I am currently developing a game that assigns a random rarity upon website loading, and I am looking to customize the color of each rarity. Here is how it appears at the moment: https:/ ...

Unable to access /route upon refreshing page in Angular 7

After developing several components in Angular 7, I decided not to use 'useHash: true' for routing. Everything seemed to be running smoothly when I deployed my Angular app on a live server. However, I encountered an issue when reloading a page a ...

Animating the height of a div based on a condition with *ngIf and CSS

I am working with an angular bloc contained within a container that displays based on a *ngIf condition. <div class="simulation-bloc"> <ng-container *ngIf="type==='simulation'"> // bloc content </ng-cont ...

Exploring the process of data filtering and applying specific conditions in Angular8

Received the following sample data from an API dynamically. Seeking suggestions on how to apply conditions based on the data. ...

Trigger a change event for a Material Checkbox by referencing its unique identifier

<div *ngFor="let cus of deselectedList | keyvalue" (click)="clickCheckBox('customer_'+cus.key+'_checkbox')"> {{cus.key}} <mat-checkbox id="customer_{{cus.key}}_checkbox" (change ...

Obtain the hexadecimal color code based on the MUI palette color name

Is there a way to extract a hexcode or any color code from a palette color name in Material UI? Here is my use case: I have a customized Badge that I want to be able to modify just like the normal badges using the color property. The component code looks ...

Is it true that Angular libraries are incompatible with PrimeNG?

Struggling with integrating primeng into an Angular library? You're not alone. Here are the steps I took: First, I generated a new Angular library using the command: ng g library generales Next, I attempted to install primeng into the generated lib ...

Send users to the login page if they are not authenticated

Why is my middleware crashing after redirecting to the login page? import type { NextRequest } from "next/server"; import { NextResponse } from "next/server"; // To avoid crashing, this function can be marked as `async` if using `await ...

How can I modify the body background or background-color when navigating routes in Angular 4?

Is there a way to update the body background or background-color when changing routes in Angular 4? ...

How can you switch alignment from left to right when the current alignment settings are not functioning as expected in HTML?

I need the buttons +, count, and - to be right-aligned on my page. The numbers on the right are taking up the same amount of space, while the names on the left vary in length. I want the buttons to always remain in the same position, regardless of the name ...

Step-by-step guide on importing jquery-ui into Angular 4

I am looking to implement the toggle function from jquery-ui into my angular application. I have successfully installed jquery-ui using npm: npm install jquery jquery-ui Following the advice provided in this answer, I included the path in the angular-cli ...

Ways to retrieve data from ngrx and display it in a component file

I have recently incorporated the ngrx library into my project to create a more dynamic model for handling data. After setting up my actions, reducers, and effects files, everything seems to be working as intended because I can observe the populated model w ...

Unable to display Cell Properties in Angular using CKEditor 5 table toolbar configuration

While utilizing the CKEditor 5 official demo, I noticed that the table content Toolbar includes Cell properties. This feature is crucial for my needs, but despite configuring my table similarly to the demo setup, the Cell properties do not appear. The dem ...

Is it better to keep a lengthy array in the back-end or front-end storage?

I'm facing a dilemma in my angular application. I have a lengthy array that I need to access easily from the front-end without causing any slowdowns. There are various options available, but I'm unsure which one would be the most efficient. Shoul ...