J'ai un appel de service http qui nécessite deux paramètres lors de son envoi:
@Injectable()
export class InvoiceService {
. . .
getInvoice(invoiceNumber: string, zipCode: string): Observable<Invoice> {
. . .
}
}
Comment puis-je transmettre ces deux paramètres à this.invoiceService.getInvoice()
dans mon effet?
@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);
})
}
Vous pouvez accéder à la charge utile dans l'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))
}
Ou vous pouvez utiliser la fonction toPayload
de ngrx/effects
pour mapper la charge utile de l'action:
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))
}
Dans @ ngrx/effects v5.0, la fonction utilitaire toPayload
a été supprimée, elle est déconseillée depuis @ ngrx/effects v4.0.
Pour plus de détails, voir: https://github.com/ngrx/platform/commit/b390ef5
Maintenant (depuis la v5.0):
actions$.
.ofType('SOME_ACTION')
.map((action: SomeActionWithPayload) => action.payload)
Exemple:
@Effect({dispatch: false})
printPayloadEffect$ = this.action$
.ofType(fromActions.DEMO_ACTION)
.map((action: fromActions.DemoAction) => action.payload)
.pipe(
tap((payload) => console.log(payload))
);
Avant:
import { toPayload } from '@ngrx/effects';
actions$.
ofType('SOME_ACTION').
map(toPayload);