Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically.

export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => IState {
  reducerName.plural = reducerName.plural ? reducerName.plural : reducerName.singular + 's';

  return function (state = initialState, action: any): IState {
    switch (action.type) {

        case `[${reducerName.plural} Section] Load Statistics ${reducerName.singular}`:
        case `[${reducerName.plural} Section] Load Details ${reducerName.singular}`:
        case `[${reducerName.plural} Section] Load ${reducerName.plural}`:
            {
                return { ...state, loading: true, loaded: false };
            }
            ...
}

and implementing it like this

export const adapter: EntityAdapter = createEntityAdapter();

export const initialState: State = adapter.getInitialState({
    loaded: false,
    loading: false,
    selectedId: null
});

export const reducer = generateReducer(initialState, { singular: 'Skill' }, adapter);

While everything works smoothly when testing the project with ng-serve (excluding AOT mode), encountering an error occurs when attempting to build for production using ng build --prod:

ERROR in src\app\skills\skills.module.ts(46,45): Error during template compile of 'SkillsModule' Function calls are not supported in decorators but 'generateReducer' was called in 'reducers' 'reducers' references 'reducers' 'reducers' references 'reducer' at src\app\skills\store\reducers\index.ts(18,13) 'reducer' calls 'generateReducer' at src\app\skills\store\reducers\skills.reducer.ts(26,24).

I've explored various solutions to resolve this issue but it seems like I need to provide some form of indication to the compiler to recognize it as a compile-time function that produces code. Any suggestions on how to tackle this kind of challenge?

UPDATE:

I have included a stackblitz repository to showcase the error,

https://stackblitz.com/edit/reducer-factory-ngrx

Feel free to download the application, update the package.json devDependencies "@angular/cli": "^1.6.0", and test running 'ng build --prod'

Answer №1

Make sure to include the following code in your "reducer.ts":

  export const reducer = generateReducer(initialState, { singular: 'Skill' }, adapter);

import { ActionReducerMap } from '@ngrx/store';
import { InjectionToken } from '@angular/core';

 // register reducer token
 export const reducerToken = new InjectionToken<ActionReducerMap<State>>(
   'Registered Reducers'
 );
 Object.assign(reducerToken, reducer);

 export function getReducers() {
   return reducer;
 }

Additionally, add this code in your app.module.ts file:

import { reducerToken, getReducers } from './reducer';


@NgModule({
imports: [
    BrowserModule,
    FormsModule,
    StoreModule.forRoot(reducerToken)
 ],
 declarations: [AppComponent, HelloComponent],
 providers: [
  {
    provide: reducerToken,
    useFactory: getReducers
  }
 ],
 bootstrap: [AppComponent]
})

I followed these steps and it worked perfectly for me. Hope this solution helps you as well!

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

"Utilizing the Ajax ScriptManager for Effective Namespace Management

After incorporating my Ajax webservice into a namespace (MyCompany.Web.MyService), I encountered an issue where the proxy in Javascript is being regenerated as MyCompany.Web.MyService. Is it possible to change the name of the Javascript proxy to just MySe ...

Generating TypeScript Type Definitions for dynamic usage

In my client server application, I use REST calls for communication. To avoid using the wrong types by mistake, I have defined all RestCalls in a common file (excerpt): type def<TConnection extends Connections> = // Authentication ...

The method hasOwnProperty does not function as intended

Upon receiving a JSON object from the server ({error:true}), I attempted to verify if the key "error" exists. Surprisingly, the function hasOwnProperty returned false. Here is the snippet of code that led to this unexpected result: $http({ header ...

Encountering a configuration error in the Nginx.conf file while attempting to use

I recently obtained a Visual Studio solution that includes multiple projects. https://i.sstatic.net/HuRyl.jpg A Nginx.conf file was created in ClientApp/Angular. https://i.sstatic.net/CN65e.jpg This is my docker-compose file: clientapp: image: ${DOCKER ...

Whenever attempting to choose a rating, the MUI dialog continuously refreshes and resets the selected rating

I'm facing an issue with my MUI dialog where it keeps refreshing and resetting the selected rating every time I try to rate a movie. Any assistance on this matter would be highly appreciated. The RateWatchMovieDialog component is designed to display ...

Trouble with feedback form not showing up

I've been working on creating an ajax feedback form, but I'm facing difficulties in getting it to show up properly. The feedback image appears, but clicking on it doesn't trigger any action. Here's my Form: <div id="feedback"> ...

Locate all buttons on the page that have an onclick function attached to them, and

I seem to have run into an issue. I am currently working with Java and WebDriver. My goal is to navigate to , locate the item "ipod", receive 4 results, and then compare them by clicking on the "compare" button beneath each item. However, I am encounteri ...

The modifications made to a bound value in AngularJS directives do not propagate to the outside components

I've been experimenting with bound variables inside directives, but I'm facing an issue where the view doesn't seem to refresh. Despite the model updating correctly (as seen in the console log) and calling $apply(), the view remains unchange ...

What potential issues can arise when importing a default export alongside a named export and using webpack in conjunction with babel?

I have two distinct constructors in my codebase: SignUp and GoogleSignIn. They are structured as follows: import SignUp, {gapi_promise} from "./SignUp"; /** * * @param element * @extends SignUp * @constructor */ function GoogleSignIn(element){ SignUp ...

When you compile TypeScript with the target set to 'ES3' or 'ES5', it creates an internal structure

Recently delved into the world of TypeScript and experimenting with webpack ts-loader and babel-loader to compile and transpile TypeScript into ES5. However, I came across a compiler option in tsc that can target 'ES5', which made me question the ...

What is the best way to use Promise.all() to delay the return of an array that is currently being constructed within the function?

In the following code block, I am trying to set an array as the value for a local variable by calling a function that returns an array. The issue arises because the Promises in the second function are not resolved until after the array has been returned to ...

Show a particular attribute from an array

My goal is to create a function that displays only minivans from an array of cars when a button is pressed. However, I'm having trouble getting anything to display when the button is clicked, even though there are no errors in the program. Any advice ...

Using Node http-middleware-proxy and integrating it with Express to communicate with Tomcat server

We have set up our Java application (which is spring based) in a Tomcat container, with the UI modules also running in the same environment. When we access Tomcat directly through http://localhost:8080, a login page is displayed and then a 302 redirect occ ...

Are variables initialized before the execution of ajax?

After reviewing the code snippet provided below, can we confirm with certainty that the id variable passed in the ajax call will consistently be assigned a value of 1? Or is there a possibility that the id could potentially be null or undefined at some p ...

Tips for troubleshooting my website?

After making some updates to my website, I noticed that an ajax script is no longer functioning properly. Since I hired someone else to write the code, I'm not sure how to troubleshoot it. Initially, this is what it should look like: When you select ...

Error arises on Github when submitting a pull request due to a conflicted package

When facing conflicts in the package.json file while submitting a pull request, what is the best approach to resolve them? I usually attempt using git pull origin, but it tends to generate numerous merge commits. ...

Determining season goals for teams using nested JSON data

Is it possible to retrieve a team's total goals scored for the season from the provided data by using the team's name as the input for a function? Would it be accurate to attempt mapping over the rounds and filtering matches where either team1 o ...

The UI in PrimeNG dropdown does not reflect changes made with patchValue()

Currently, I am working on a reactive form that includes a few fields - three dropdowns and one calendar. These fields are all PrimeNG components. Interestingly, all fields except for the project field successfully update their values in the user interface ...

Request a HTML variable and send it to JavaScript

My latest project involves a Binary to Decimal Calculator that is now fully functional, but I am looking to integrate an HTML input into it. <html> <input placeholder="00000000" name="htmlinput"></input> <input id="clickMe" type="butt ...

Are there any instances of a race condition present in the following?

In the express server code snippet provided, there is a common object that is being manipulated in three different RESTful endpoints. Given that all HTTP requests in Node.js are asynchronous, it's possible to have simultaneous PUT and GET requests occ ...