Angular 5 does not allow function calls within decorators

I encountered an issue while building a Progressive Web App (PWA) from my Angular application. When running ng build --prod, I received the following error:

ERROR in app\app.module.ts(108,64): Error during template compile of 'AppModule'
Function calls are not supported in decorators but 'Environment' was called in 'environment'
'environment' calls 'Environment'.

The error seemed confusing as I had already added export to the class, which is evident from the code snippet below:

environment.prod.ts

import { BaseEnvironment } from './base-environment';
import { ProspectBuilderModel } from '../app/models/prospect';

export class Environment extends BaseEnvironment {
  production: boolean = true;
  prospectBuilderModel: ProspectBuilderModel = {
    buildQuote: false,
    // other properties...
  };
}

export const environment = new Environment();

base-environment.ts

import { ProspectBuilderModel } from '../app/models/prospect';

export abstract class BaseEnvironment {
  abstract production: boolean;
  abstract prospectBuilderModel: ProspectBuilderModel;
}

app.module.ts

...
 ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    MultiselectDropdownModule,
    ReactiveFormsModule,
    HttpModule,
    ToastrModule.forRoot(),
    BrowserAnimationsModule,
    NgxMyDatePickerModule.forRoot(),
    PopoverModule.forRoot(),
    ModalModule.forRoot(),
    ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })
  ],
  providers: [
...

If anyone has ideas on how to resolve this error, please let me know.

Answer №1

Encountered the same issue, here are some potential solutions (if dynamically loaded properties are not a concern):

1. Utilize an object as your response.

This approach may result in losing default properties and details regarding "to implement" properties.

2. Implement static classes:

In this scenario, you may lose 'to implement' properties since abstract statics are not feasible. However, you will still retain the types and defaults.

// default.env.ts
export class BaseEnvironment {
  public production: boolean = true;
  public specialPropToImpl: boolean = true;
}

// your.env.ts
export class Environment extends BaseEnvironment {
  public specialPropToImpl = true;
}

export const environment = Environment;

3. Implement default properties object, interface, and object assignment:

This method allows for retaining the 'to implement' properties, types, and defaults, albeit it may be slightly cumbersome to implement.

// default.env.ts
export interface EnvProperties {
  production: boolean;
  specialPropToImpl: boolean;
}

export const defaultEnv = {
  production: true
};

// your.env.ts
export const environment: EnvProperties = {
...defaultEnv,
specialPropToImpl: true
};

4. Introduce just one additional static variable from environment

A straightforward solution which involves maintaining your subclasses, however, every env file must have it. This method could work well considering new environment files are typically created by replicating existing ones.
Depending on the production value, you would need to manually adjust the variable value.
While not incredibly flexible or easy to maintain, this solution is simple.

// your.env.ts
export const enablePwa = true

// app.module.ts
import {environment, enablePwa} from 'env.ts'
//...
ServiceWorkerModule.register('/ngsw-worker.js', { enabled: enablePwa })

Answer №2

It seems like your code was functioning properly until you inserted the line ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })

Typically, when we reference the environment variable in the app module, it usually points to the environment files automatically created by Angular CLI (which serve as constants and are exported accordingly). I have never attempted to instantiate a class object and pass it in the app module before. This could be the root of the issue.

Consider simply passing true directly into this line instead of fetching it from an object to test if that resolves the problem.

Answer №3

Check out the code snippet below for the solution I eventually figured out. Hopefully, this will be useful for anyone facing a similar issue in the future. Basically, all I did was tweak my environment file to avoid creating an instance of the Environment class. It seems like Angular doesn't quite approve of instantiating it:

export const environment = {
  production: true,
  prospectBuilderModel: {
    buildQuote: false,
    buildAcknowledge: false,
    buildOrganizationInfo: false,
    buildFinancialInfo: false,
    buildTradeInfo: false,
    buildPermissiblePurpose: false,
    buildUserSetup: false,
    buildPackageSelection: false,
    buildPaymentOptions: false,
    buildOrderOptions: false,
    buildVerifyOrganizationInfo: false,
    buildDocusignAuthorization: false,
    buildDocusignContract: false
  }
}

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

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

How to exit a dialog in an Angular TypeScript component with precision

Hey there, I'm attempting to close a dialog from the component by specifying the path in .angular-cli.json and calling the function. However, it seems that despite my efforts, the dialog isn't closing and the redirection isn't happening. He ...

Retrieve data upon component mounting and deactivate the query in React-query

When navigating to a search result page, query parameters are passed to useQuery. I want the data to be fetched only when the user clicks the "Search" button after changing the search prompt. I attempted to use enabled: false and call refetch() on button ...

Angst with the Angular Command Line Interface

After installing the Angular CLI via the command prompt, I encountered an error related to @angular-devkit/build-angular. However, everything else seems to be working fine. Does anyone have any ideas as to why this might be happening? https://i.stack.im ...

Oops! The module "rxjs/Subject" seems to be missing the exported member "Subject"

Here is the code I'm working with: import { Subject } from 'rxjs/Subject'; Upon importing this, an error occurs: rxjs/Subject" has no exported member 'Subject'. I am unable to fix this issue. Does anyone have a solution? ...

Evaluate the Worth of a Property Established in a Subscription

Currently, I am using Jasmine for testing an Angular application and facing a challenge in testing the value of a property that is set within the subscribe call on an Observable within the component. To illustrate this point, I have created an example comp ...

having difficulty applying a border to the popup modal

Currently, I am utilizing a Popup modal component provided by the reactjs-popup library. export default () => ( <Popup trigger={<button className="button"> Guide </button>} modal nested > {(close: any) =&g ...

Tips for incorporating recursive HTTP requests into an Angular2 service to efficiently retrieve data in advance

In my Angular project, I am using a service to fetch data from an external API. However, the API has a limit of 100 records per request and I can only determine the total number of records available after fetching the first batch. The response structure o ...

The index access type cannot be used with T[Key extends keyof T]

My work frequently involves arrays structured like this: [ {key1: val1, key2: value2, key3: val3}, {key1: val1, key2: value2, key3: val3}, {key1: val1, key2: value2, key3: val3}] and I often need to convert them into a dictionary/map format, for example: ...

Determining the Type<> of a component based on a string in Angular 2

Can you retrieve the type of a component (Type<T>) based on a string value? For example: let typeStr: string = 'MyComponent'; let type: any = getTypeFromName(typeStr); // actual type ...

"Looking to personalize marker clusters using ngx-leaflet.markercluster? Let's explore some ways to customize

I am currently struggling to implement custom cluster options in ngx-leaflet. My goal is simply to change all marker clusters to display the word "hello". The demo available at https://github.com/Asymmetrik/ngx-leaflet-markercluster/tree/master/src/demo/a ...

Acquiring information from a Service and saving it in a Child component - Angular version 11

Utilizing my service, I fetch API data for the child component. Initially, it retrieves the Id and other user data, displaying it in the console. ngOnInit(): void { this.commonService.userSetChange.subscribe( apiData => { this.getUserS ...

How to arrange table data in Angular based on th values?

I need to organize data in a table using <th> tags for alignment purposes. Currently, I am utilizing the ng-zorro table, but standard HTML tags can also be used. The data obtained from the server (via C# web API) is structured like this: [ { ...

Capturing a webpage through Record RTC integration with Angular

I am looking to record a specific section of the page as a video with audio. For example, when a user enters the page, I want it to automatically start recording the activities in that particular area (similar to how iframe videos work). The recording sh ...

The user type is not yet loaded from Firestore when the view is rendered

I am currently in the process of developing an Ionic - Angular application that allows hospital patients to submit requests to nursing staff, who can then view the assigned requests based on the patient's room. Nurses have access to all requests, whil ...

Downcasting on "this" is not supported in Typescript

In the example below, the TypeScript compiler does not allow for a direct cast of this to Child. However, it is possible to achieve this using an intermediate variable like 'temp' or double casting as shown in the commented lines. Is this behavio ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

ngFor filter based on user input

I am working on a 2-step stepper feature where I need to filter the values in my amountArray based on the age of the person. If the person is above 50 years old, display only the values 10000 and 15000. For Euro currency, show values 25000 and 50000. I att ...