如何在Angular 2中访问ngrx效果中的参数?

Bra*_*don 14 ngrx angular

我有一个http服务调用,在调度时需要两个参数:

@Injectable()
export class InvoiceService {
  . . .

  getInvoice(invoiceNumber: string, zipCode: string): Observable<Invoice> {
    . . .
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何随后将这两个参数传递给this.invoiceService.getInvoice()我的效果?

@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);
    })
}
Run Code Online (Sandbox Code Playgroud)

car*_*ant 16

您可以访问操作中的有效内容:

@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))
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用toPayload函数ngrx/effects来映射操作的有效负载:

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))
}
Run Code Online (Sandbox Code Playgroud)


eli*_*lim 6

在@ ngrx / effects v5.0中,该实用程序功能toPayload已删除,自@ ngrx / effects v4.0起已弃用。

有关详细信息,请参见:https : //github.com/ngrx/platform/commit/b390ef5

现在(从v5.0开始):

actions$.
  .ofType('SOME_ACTION')
  .map((action: SomeActionWithPayload) => action.payload)
Run Code Online (Sandbox Code Playgroud)

例:

@Effect({dispatch: false})
printPayloadEffect$ = this.action$
    .ofType(fromActions.DEMO_ACTION)
    .map((action: fromActions.DemoAction) => action.payload)
    .pipe(
        tap((payload) => console.log(payload))
    );
Run Code Online (Sandbox Code Playgroud)

之前:

import { toPayload } from '@ngrx/effects';

actions$.
  ofType('SOME_ACTION').
  map(toPayload);
Run Code Online (Sandbox Code Playgroud)