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

标签 angular ngrx

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

@Injectable()
export class InvoiceService {
  . . .

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

我如何随后将这两个参数传递给我的 Effect 中的 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);
    })
}

最佳答案

您可以在操作中访问负载:

@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))
}

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

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))
}

关于angular - 如何在 Angular 2 的 ngrx 效果中访问参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40581991/

相关文章:

angular - 如何使用 Angular2 和 typeScript 将输入实时转换为星号

angular - 在 Angular cdk 叠加层上获取事件位置?

javascript - NGRX Action /效果上的多个有效负载

javascript - 如何在 ngrx/effect (redux-observable) 中分派(dispatch)多个 Action ?

angular - webpack 是否打包 .angular-cli.json 中引用的文件?

css - 如果组件被破坏,如何删除特定的 scss?

angular6 - Angular 6 ng lint select 已弃用

angular - NgrxStore 和 Angular - 大量使用异步管道或在构造函数中只订阅一次

angular - switchMap 使用 Angular http 客户端保留/取消请求

angular - 通过唯一 ID 识别 Angular 组件实例