Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parameters in an ngrx effect in Angular 2?

Tags:

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);
    })
}
like image 360
Brandon Avatar asked Nov 14 '16 04:11

Brandon


2 Answers

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))
}
like image 161
cartant Avatar answered Sep 20 '22 13:09

cartant


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);
like image 31
elim Avatar answered Sep 18 '22 13:09

elim