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

前端之家收集整理的这篇文章主要介绍了如何在Angular 2中访问ngrx效果中的参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个http服务调用,在调度时需要两个参数:
@Injectable()
export class InvoiceService {
  . . .

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

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

猜你在找的Angularjs相关文章