I have a http service call that requires two parameters when dispatched:
@Injectable()
export class InvoiceService {
. . .
getInvoice(invoiceNumber: string, zipCode: string): Observable<Invoice> {
. . .
}
}
How do I subsequently pass those two parameters to this.invoiceService.getInvoice()
in my Effect?
@Injectable()
export class InvoiceEffects {
@Effect()
getInvoice = this.actions
.ofType(InvoiceActions.GET_INVOICE)
.switchMap(() => this.invoiceService.getInvoice()) // need params here
.map(invoice => {
return this.invoiceActions.getInvoiceResult(invoice);
})
}
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))
}
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);
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