Using Angular Ngrx to Retrieve and Showcase a Selection of Choices from a Java API

When accessing the Java API at localhost://company/products/123/fetchOptions, you can expect a response similar to the following:

{ 
 "Increase": true,
 "Decrease" : true,
 "Like" : true,
 "Dislike" : true,
 "Old" : false,
 "Others" : true
}

Using Angular and ngrx on the UI, I am tasked with fetching data from the API above and displaying all 6 values as dropdown options.

The values with boolean false will be shown in the dropdown but disabled.

How can this be achieved using Ngrx?

I have some knowledge about defining Interfaces, creating Actions, and setting up dispatchers so that I can subscribe to them in my UI component (productAttributes.component.ts).

What should my interface look like and what other steps are needed? I am currently using JSON for testing purposes, but will eventually replace it with the actual API URL.

Thank you in advance for any assistance...

Answer №1

Here are the steps you need to take:

  • Create a feature for your store
  • Define a reducer
  • Define a selector
  • Create a load action
  • Create a success action
  • Create a failure action
  • Create an effect

Reducer


export const optionsFeatureKey = 'options';

export const optionsLoad = createAction(
    'options:load',
);

export const optionsSuccess = createAction(
    'options:success',
    props<{ data: OptionsState }>(),
);

export const optionsFailure = createAction(
    'options:failure',
);


export interface OptionsState {
    Increase: boolean;
    Decrease: boolean;
    Like: boolean;
    Dislike: boolean;
    Old: boolean;
    Others: boolean;
}

export const initialState: OptionsState = {
    Increase: false,
    Decrease: false,
    Like: false,
    Dislike: false,
    Old: false,
    Others: false,
};

const reducer = createReducer(
    initialState,

    on(optionsSuccess, (state, {data}) => ({
        ...state,
        ...data,
    })),

);

export function optionsReducer(state: OptionsState | undefined, action: Action): OptionsState {
    return reducer(state, action);
}

export const optionsFeature = createFeatureSelector<OptionsState>(optionsFeatureKey);

export const getOptions = createSelector(
    optionsFeature,
    v => v,
);

Effect


@Injectable()
export class OptionsEffects {
    public readonly load$: Observable<Action> = createEffect(() =>
        this.actions$.pipe(
            ofType(optionsLoad),
            switchMap(() => this.http.get<OptionsState>(`url.com`).pipe(
                map(data => optionsSuccess({data: data})),
                catchError(() => of(optionsFailure())),
            ),
        ),
    );

    constructor(
        protected readonly actions$: Actions,
        protected readonly http: HttpClient,
    ) {}
}

And somewhere in your app

store.dispatch(optionsLoad());

store.select(getOptions).subscribe(options => {
  // Add your logic here.
});

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

What is the best technique for evaluating different businesses' operating hours?

I am trying to compare the opening hours stored on my server with the current time. Here are the details: Start: 09.00 End: 00.30 The goal is to determine if the store is open or closed based on the current time. If the current time falls outside of t ...

What is the best way to create a compound query in Firebase?

I am working on a TypeScript script to search for a city based on its population... import { getFirebase } from "react-redux-firebase"; ... get fb() { return getFirebase(); } get fs() { return this.fb.firestore(); } getCollection(coll ...

Can you please explain the purpose of this function?

I came across this code snippet on a website and I'm curious about its function and purpose. While I'm familiar with PHP, HTML, CSS, and JavaScript, I haven't had the chance to learn JQUERY and AJAX yet. Specifically, I'm interested in ...

Angular 4: Loading components sequentially

I am currently working with Ionic 3 and based on the Angular 4 framework. I have a question regarding loading multiple children components asynchronously, one by one: Load parent component; Load first child component; After the first child component is l ...

Having trouble with @HostListener on iPad or iOS devices? I'm currently using a Bluetooth keyboard to navigate and interact with an Angular app

I am currently creating a web application using Angular 6 for an iPad with a screen size of 9.7 inches. I have implemented code similar to the one found at this link. import { Component, HostListener } from '@angular/core'; export enum KEY_CODE ...

Transforming Unicode escape sequences into symbols and displaying them in a DOM element

Using the latest versions of Firefox and Chrome with jQuery 1.x edge. When an ajax request returns a single line of minified JSON text like this: { "fromSymbol": "\\u04b0", "toCurrency": "AUD", "toSymbol": "\\u0024", "convFact ...

Experimenting with throws using Jest

One of the functions I'm testing is shown below: export const createContext = async (context: any) => { const authContext = await AuthGQL(context) console.log(authContext) if(authContext.isAuth === false) throw 'UNAUTHORIZED' retu ...

updating the v-model in Vue.js datepicker retains the previously set value while setting a new date

When using the template, the endDate updates as expected. However, there seems to be an issue when the filtersChanged method is called with the @selected attribute - the updated value is not the new one but rather the previously set value. <template&g ...

Is it possible for an AJAX request to return both HTML data and execute callback functions simultaneously?

Is it possible to update the content of an HTML div and call a JavaScript function with specific parameters obtained through AJAX after the completion of the AJAX request, all within a single AJAX call? ...

NodeJS's pending ajax post using SailsJS

I'm experiencing an issue with processing AJAX data in my sailsJS app. The ajax post data always stays in the pending state, here is the code from my view: <script type="text/javascript"> $('#submit').click(function(){ $.ajax ...

Having trouble changing my array state in react?

I'm having trouble understanding why my React state isn't updating with the following code: state = { popUpMessages:[] } popUpMessage(id,name) { console.log("id ",id,"name ",name) const addUserObject = { id, name }; const new ...

Utilizing slid.bs.carousel to retrieve values upon slide change

I am working on incorporating Bootstrap 4's Carousel with jQuery and PHP to create an odometer that dynamically changes its value on each slide. My plan is to utilize .addClass based on the length of the value. One challenge I am facing is that when ...

What is the best way to dynamically change the color of my component depending on the prop passed to it?

I am facing an issue with the color of my component changing based on the value of the prop 'level'. Despite using states to set the backgroundColor, all components end up having the same color due to the state being altered for every comment. I ...

On startup of the chrome app, read and load a JSON file into a variable

As I develop a chrome app, my goal is to store all configuration defaults in json file(s) alongside other assets. I am currently using AJAX requests to load them, but I'm wondering if there is a more efficient way to handle this. Is there perhaps an o ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

Is it possible to modify the sub/child divs within a draggable parent div and assign them a different class?

Greetings, after being a long-time reader, I have finally decided to post for the first time. In the process of creating a webpage with jQuery drag and drop divs, I am curious about how to change the class of a child div within a draggable div once it is d ...

What is the process for retrieving the parent component from projected content?

One interesting aspect to explore is the varying behaviors of input based on its 'parent' element. The structure I am referring to is as follows: In my first example, the input is nested within the app-chip-list component. APP COMPONENT HTML & ...

Can multiple print buttons in different modals be connected to individual divs within their respective modals?

I am currently developing a webpage using the Foundation 5 framework that features a table of information. Each row in the table contains a link that, when clicked, opens a specific modal displaying detailed information related to that row. I want to add a ...

:onchange event triggering iteration through a function

My Vue.js application is experiencing issues with infinite post requests when a selectbox value changes. I have a table component that needs to display students from different 'tutorgroups'. Each tutorgroup, like '4M07a', has its own se ...

Automatically adjust the model input (Signal) based on the parent and respond to any alterations in the children

Within my Angular 16 application, I have a parent component that passes a plain JavaScript object (myObj) to a child component, where it is treated as a model<MyObj>. <!-- parent.component.html --> <app-children [myObjModel]="myObj&qu ...