user11364823
user11364823

Reputation:

Angular Ngrx: Getting & displaying list of options from Java API

Java API would be - localhost://company/products/123/fetchOptions Its response would be like same below :

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

Now on UI using Angular & ngrx i need to include changes to fetch data from above API and display all 6 values above as dropdown Options.

The value with boolean false will be shown in dropdown but would be disabled.

How to do that using Ngrx ?

i know a bit about it, that first i need to define Interface, then Any Action followed by its dispatcher so that i can subscribe to it in my UI component (productAttributes.component.ts).

How would be my interface like and other things ? Currently using JSON to make everything ready, later will replace JSON url with API

Thanks in advance for help...

Upvotes: 2

Views: 777

Answers (1)

satanTime
satanTime

Reputation: 13574

You need to:

  • create a store feature for it
  • 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 => {
  // logic.
});

Upvotes: 2

Related Questions