AOT throws a `TypeError: Attempting to assign a value to a read-only property`, exclusively on AOT

An older project of mine was originally created in Angular 7. Recently, I felt inspired and decided to update it to version 13. During development, everything seemed to work fine. However, when I attempted to compile the project using ng serve to deploy it on my server along with the API, I encountered an error:

ERROR TypeError: "count_categories" is read-only
    Dictionary dictionary.ts:8
    set dictionaries.service.ts:34
    getAll dictionaries.service.ts:84
    (..)

The issue seems to be related to "Strict Mode", as the code runs smoothly on serve but crashes during AOT compilation.

The problematic section in the code can be found in the constructor of the Dictionary class:

public constructor(init?: any) {
    Object.assign(this, init); // The error is here
}
id: number;
name: string;
language: string;
dateCreated: Date;
dateRevision: Date;
@Optional() changes: boolean;
@Optional() novel: Novel[];
// tslint:disable-next-line: variable-name
@Optional() count_categories: [{count: number}];

countCategories(): number {
    if (this.count_categories[0]) {
        return this.count_categories[0].count;
    }
    return 0;
}

This error arises from assigning a value to the optional array "count_categories" using Object.assign which leads to the read-only issue during AOT compilation. Despite attempts to disable Strict Mode, the problem persists. Any suggestions for resolving this issue or alternative approaches would be greatly appreciated.

The data provided by the API looks like this:

{
    "id": 1,
    "name": "asd",
    "language": "English",
    "dateCreated": "2019-05-28T01:29:13.000000Z",
    "dateRevision": "2022-01-14T17:56:34.000000Z",
    "count_categories": [
        {
            "idDictionary": 1,
            "count": 14
        }
    ]
}

The challenge lies in finding a solution to overcome the read-only error during AOT compilation in Angular. Your insights and expertise are welcome in identifying a workaround or resolution for this perplexing issue.

As someone relatively unfamiliar with Angular, I seek guidance on how best to address this technical hurdle and leverage the platform's capabilities effectively.

Answer №1

As I continued working on the project, I noticed that while it was functioning perfectly with serve, there seemed to be a problem when trying to compile and then serve again. It appeared that the issue persisted and the functionality stopped.

Initially, I suspected that the issue could be related to assigning values to an object. So, I adjusted the API to directly provide the required number (count), but the problem still persisted. Surprisingly, removing @Optional resolved the issue...

Upon further investigation, I realized that for my specific requirements, all calls should return the value even though the original value was optional. While this may not be ideal, it seems to work in practice. However, I am eager to discover better ways to understand and address such "limitations".

Regarding the parts that I anticipated would change, it appears that I neglected to implement those updates. Although it is not currently affecting me, I have plans to enhance flexibility in the future.

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

Angular Error: Potential security risk detected in resource URL context due to unsafe value being used

Hey there, I'm looking to display a dynamic pdf file. Initially, I encountered a CORS error, but managed to resolve it by using DOM Sanitizer. However, now I'm facing an issue with unsafe URLs. Any assistance would be greatly appreciated. Below ...

Emailjs package integration in Angular 7 seems to be facing some setbacks

Just diving into Angular and running into issues trying to use the "emailjs" package in Angular 7. Any tips on getting it up and running? Test code is the same as the original source Even after making modifications (see source for hints) in the file "node ...

The width of the Bootstrap tooltip changes when hovered over

Currently, I am facing a peculiar issue with my angular web-application. Within the application, there is a matrix displaying data. When I hover over the data in this matrix, some basic information about the object pops up. Strangely, every time I hover ov ...

Error: The property 'attach' of undefined is not readable in makeStyles.js

Encountering a series of type errors when attempting to access the Login component of my MERN app on the production version, as shown in this image: https://i.sstatic.net/6apXu.png The app (https://github.com/ahaq0/kumon_schedule) functions perfectly on ...

Which is the best option: Service variable, Service Observable, or Service Subject?

Lately, I've been contemplating the idea of global variable declaration, and I'm struggling to see the advantage of using a Subject in a service instead of a simple variable or even an Observable. Could you help me understand why someone would ch ...

Discovering the best method to retrieve user details (email address) following a successful login across all pages or components within Angular

Discovering the world of Angular and TypeScript is quite exciting. In my Angular project, I have 8 pages that include a login and registration page. I'm facing an issue where I need to access the user's email data on every page/component but the ...

Problem with Typescript and packages.json file in Ionic 3 due to "rxjs" issue

I encountered a series of errors in my Ionic 3 project after running ionic serve -l in the command terminal. The errors are detailed in the following image: Errors in picture: https://i.sstatic.net/h3d1N.jpg Full errors text: Typescript Error ';& ...

Integrating Paytm with Angular 6: A Step-by-

I am currently facing an issue where I am not being redirected to the paytm server's page after using the HTML form for integrating paytm in PHP. Can anyone provide assistance with this matter? ...

Ways to enable an Angular 5 web application to launch in multiple tabs within a single browser

Is there a way to open an Angular 5 app in multiple tabs of Chrome? Are there any methods or caching processes that can assist with this task? ...

Bringing in functions from another class in TypeScript: A step-by-step guide

I am looking to import another class, specified by a name string (for example, 'B'), into the current class (named 'A'). The function in class B needs to be able to call a function in class A. I am seeking guidance on how to achieve thi ...

Using cdk's virtual scroll feature in conjunction with the mat-grid-list component

Are there any virtual scrolling options that can be integrated with a grid-list? I believe the standard implementation may not suffice as each row requires a surrounding element. I am currently utilizing the grid-list to showcase profile pictures, and req ...

Angular 2 does not automatically re-evaluate *ngIf on model change

I am working on a navigation bar that consists of 2 buttons. My goal is to display only the button for the other page and disable the button for the current page. Currently, when I navigate to the settings page, the settings button is hidden. However, whe ...

How to Merge Items within an Array of Objects Using Typescript?

I'm currently facing a challenge in combining objects from an array of Objects in typescript. The structure of the array is as follows: 0: {type: 'FeatureCollection', features: Array(134)} 1: {type: 'FeatureCollection', features: ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

Developing a Customized Filtering Mechanism in Angular 8

I have some experience working in web development, but I am relatively new to Angular. My current project involves creating a simple filter for a table's column based on user input. However, I'm facing an issue where typing in a single letter fil ...

Looking to simulate a constant instance that has been exported

Is there a way to mock the export const dependendantService in order for me to provide a mock result for dependendantService.list? The list contains a `get` method but it is read-only. I have attempted to mock the module or use jest.spyOn(dependendantServ ...

Handling linting errors for getInitialProps return type in NextJS with Typescript

I've been grappling with this problem for an extended period, and despite numerous attempts, I haven't been able to resolve it. My issue revolves around a basic page named one.tsx. Its structure is as follows: https://i.sstatic.net/xP89u.png T ...

Utilizing an AwsCustomResource in AWS CDK to access JSON values from a parameter store

I found a solution on Stack Overflow to access configurations stored in an AWS parameter. The implementation involves using the code snippet below: export class SSMParameterReader extends AwsCustomResource { constructor(scope: Construct, name: string, pr ...

Utilizing the capabilities of the Highcharts regression plugin within the Angular 8 wrapper to effectively depict a trend line on a

Currently, I am attempting to incorporate a trendline into my spline plot using the Highcharts regression plugin. However, I'm struggling to locate any guidance on how to properly import the highcharts-regression plugin within my Angular component. I ...

React-router-dom error: Unable to locate any routes for the specified location '/' due to Route parameter

Currently, I am facing an issue with passing a parameter using React-router-dom's Link and Route. Here is how my routes are set up: In my App.tsx file: <Routes> <Route path="/:id" element={<Home />} /> <Route ...