I am trying to send id parameter from the dispatch to the effect, I can't find any example of this case in google.
Here's the code I already have:
The component:
ngOnInit(): void {
this.packageClass = `type-${this.package.packageType.toLowerCase()}`;
// I set the payload to the action
this.store.dispatch(new LoadClusterInfo({id: this.package.id}));
this.checkStatus();
}
The effect (where I need to access the value)
@Effect()
getClusterInfo =
this.actions.ofType(resultActions.Type.LOAD_CLUSTER_INFO)
.pipe(
switchMap(() => {
let id = 'HARDCODED_ID';
return this.service.getPackageCluster(id); // Here is where i need the value
}),
map((packageCluster: PackageCluster) => new LoadClusterInfoSuccess(packageCluster)),
catchError((err: Error) => of(new LoadClusterInfoError(err))),
);
And last the action:
export class LoadClusterInfo implements Action {
readonly type = Type.LOAD_CLUSTER_INFO;
constructor(readonly payload: any) {}
}
How can I access the id sent by the component (this.package.id) in the effect?
For those trying to get params with mergeMap you can do it like these:
loadItems$ = createEffect(() =>
this.actions$.pipe(
ofType(YOUR_ACTION_NAME),
mergeMap((action) =>
this.myService.getAll(action.parameters).pipe(
map((items) => ({
type: ITEMS_LOADED_SUCESSFULLY,
items: itemsList,
})),
catchError(() => EMPTY)
)
)
)
);
To dispatch the action:
this.store.dispatch(loadItems({ parameters: parameter }))
And in your .actions.ts:
export const loadItems = createAction(
YOUR_ACTION_NAME, props<{ parameters: string }>());
You can access the action's payload property in the switchMap
operator.
A couple of extra things:
ofType
operator because the ofType
function is removed in NgRx 7
ofType
operator to have a typed actionmap
and catchError
on the service stream, otherwise when an error occurs the effect stream will get destroyed. See the NgRx docs for more info.@Effect()
getClusterInfo = this.actions
.pipe(
ofType<LoadClusterInfo>(resultActions.Type.LOAD_CLUSTER_INFO),
switchMap((action) => {
return this.service.getPackageCluster(action.id).pipe(
map((packageCluster: PackageCluster) => new LoadClusterInfoSuccess(packageCluster)),
catchError((err: Error) => of(new LoadClusterInfoError(err))),
);
}),
);
Update NgRx v8 +
With createAction
and createEffect
, the action is automatically inferred so you can do this and benefit from the types:
getClusterInfo = createEffect(() => {
return this.actions.pipe(
ofType(loadClusterInfo),
switchMap((action) => {
return this.service.getPackageCluster(action.id).pipe(
map((packageCluster: PackageCluster) => new LoadClusterInfoSuccess(packageCluster)),
catchError((err: Error) => of(new LoadClusterInfoError(err))),
);
}),
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With