Skip to content

Instantly share code, notes, and snippets.

@markgoho
Last active December 6, 2020 11:47
Show Gist options
  • Save markgoho/c4a5aa897186bad91ffd5dae830b0e0d to your computer and use it in GitHub Desktop.
Save markgoho/c4a5aa897186bad91ffd5dae830b0e0d to your computer and use it in GitHub Desktop.
Ngrx Effects with Nx
// Effect with no Nx added
loadBrokersBasic$ = createEffect(() =>
this.actions$.pipe(
ofType(BrokersActions.loadBrokers),
switchMap(action => {
return this.brokerApiService.getAllBrokers().pipe(
map(brokers => BrokersActions.loadBrokersSuccess({ brokers: [] })),
catchError(error => of(BrokersActions.loadBrokersFailure({ error })))
);
})
)
);
// Effect with Nx pipeable operator fetch used
loadBrokersNoDataPersistence$ = createEffect(() =>
this.actions$.pipe(
ofType(BrokersActions.loadBrokers),
fetch({
run: action => {
return this.brokerApiService
.getAllBrokers()
.pipe(
map(brokers => BrokersActions.loadBrokersSuccess({ brokers: [] }))
);
},
onError: (action, error) => {
console.error('Error', error);
return BrokersActions.loadBrokersFailure({ error });
},
})
)
);
// Effect with Nx Data Persistence Module used
loadBrokersWithDataPersistence$ = createEffect(() =>
this.dataPersistence.fetch(BrokersActions.loadBrokers, {
run: (
action: ReturnType<typeof BrokersActions.loadBrokers>,
state: fromBrokers.BrokersPartialState
) => {
return this.brokerApiService
.getAllBrokers()
.pipe(
map(brokers => BrokersActions.loadBrokersSuccess({ brokers: [] }))
);
},
onError: (
action: ReturnType<typeof BrokersActions.loadBrokers>,
error
) => {
console.error('Error', error);
return BrokersActions.loadBrokersFailure({ error });
},
})
);
@markgoho
Copy link
Author

markgoho commented Feb 6, 2020

  1. Is it just for readability that we're using the pipeable operator instead of switchMap?
  2. What does the DataPersistence module get us that the fetch operator doesn't?

Here's the source code for the DataPersistence module: https://github.com/nrwl/nx/blob/master/packages/angular/src/runtime/nx/data-persistence.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment