Angular + ngrx : Gestion des requêtes http avec ngrx/effects…

Photo by Ricardo Rocha on Unsplash

TL/DR;

Prérequis

Introduction

Initialiser le store avec les services

// snippet from myApp.reducer.ts
export interface IAppState{
data: string;
isLoading: boolean;
}
export const initialState: IAppState = {
data: "",
isLoading: false
};
export function userReducer(
state: IAppState = initialState,
action: Action
): IAppState{
switch (action.type) {
case 'INIT_DATA':
return Object.assign({}, state);
default:
return state;
}
// Anti-pattern d’exemple à ne pas utiliser// snippet from MyDataViewer.component.ts
onInit() {
this.myService.getData()
.subscribe(
(payload) => this.store.dispatch({type: 'INIT_DATA', payload})
);
}

ngrx/effects

// snippet from MyDataViewer.component.ts
onInit() {
this.store.dispatch({ type: 'INIT_DATA' });
}
// snippet from MyData.effect.ts
@Effect()
getEventStart$ = this.actions$
.ofType('INIT_DATA')
.switchMap(payload => this.myService.getData())
.map(responseBody => ({
type: 'INIT_DATA_SUCCESS',
payload: responseBody.json()
}))
.catch((err: Error) => Observable.of(getEventFailed(err))
);
// snippet from myApp.reducer.tsexport interface IAppState{  data: string;  isLoading: boolean;}export const initialState: IAppState = {  data: "",  isLoading: false};export function userReducer(    state: IAppState = initialState,    action: Action  ): IAppState{switch (action.type) {  case 'INIT_DATA':    return Object.assign({}, state, { isLoading: true });  case 'INIT_DATA_SUCCESS':    return Object.assign({}, { data: action.payload, isLoading: false });  case 'INIT_DATA_FAILED':    return  Object.assign({}, state, { isLoading: false });default:    return state;}

Pour aller plus loin…

Software engineer, amateur photographer, nature fan, lifelong learner.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store