How to access parameters in an ngrx effect in Angular 2?
In @ngrx/effects v5.0 the utility function toPayload
was removed, it has been deprecated since @ngrx/effects v4.0.
For Details see: https://github.com/ngrx/platform/commit/b390ef5
Now (since v5.0):
actions$.
.ofType('SOME_ACTION')
.map((action: SomeActionWithPayload) => action.payload)
Example:
@Effect({dispatch: false})
printPayloadEffect$ = this.action$
.ofType(fromActions.DEMO_ACTION)
.map((action: fromActions.DemoAction) => action.payload)
.pipe(
tap((payload) => console.log(payload))
);
Before:
import { toPayload } from '@ngrx/effects';
actions$.
ofType('SOME_ACTION').
map(toPayload);
You can access the payload within the action:
@Injectable()
export class InvoiceEffects {
@Effect()
getInvoice = this.actions
.ofType(InvoiceActions.GET_INVOICE)
.switchMap((action) => this.invoiceService.getInvoice(
action.payload.invoiceNumber,
action.payload.zipCode
))
.map(invoice => this.invoiceActions.getInvoiceResult(invoice))
}
Or you can use the toPayload
function from ngrx/effects
to map the action's payload:
import { Actions, Effect, toPayload } from "@ngrx/effects";
@Injectable()
export class InvoiceEffects {
@Effect()
getInvoice = this.actions
.ofType(InvoiceActions.GET_INVOICE)
.map(toPayload)
.switchMap((payload) => this.invoiceService.getInvoice(
payload.invoiceNumber,
payload.zipCode
))
.map(invoice => this.invoiceActions.getInvoiceResult(invoice))
}