How to access parameters in ngrx effect in Angular 2?

I have an http service call that requires two parameters when sending:

@Injectable()
export class InvoiceService {
  . . .

  getInvoice(invoiceNumber: string, zipCode: string): Observable<Invoice> {
    . . .
  }
}

How do I pass these two parameters in 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);
    })
}
+4
source share
2 answers

You can access the payload inside 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 function toPayloadfrom ngrx/effectsto map the action 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))
}
+8
source

In @ ngrx / effects v5.0, the utility function has toPayloadbeen removed, it is deprecated with @ ngrx / effects v4.0.

See https://github.com/ngrx/platform/commit/b390ef5 for details

Now (since version 5.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);
+1

Source: https://habr.com/ru/post/1660647/


All Articles