2016-11-14 76 views
2

我有一個需要兩個參數時調度HTTP服務電話:如何在Angular 2中訪問ngrx效果中的參數?

@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); 
    }) 
} 
+1

據推測,參數需要從商店的狀態中獲得。如果是這樣的話,有一個答案[這裏](http://stackoverflow.com/questions/39565811)。 – cartant

+0

我是ngrx的全新品牌,請耐心等待。在這種情況下,我還沒有爲商店設置任何值,我正在進行服務調用以獲取我想要存儲的數據。我是否應該將參數作爲我的'getInvoice()'動作的'payload'來傳遞? – Brandon

+0

是的,如果你沒有商店中的信息,而是信息來自組件中的輸入信息,例如,將信息放入有效載荷中將是要走的路。 – cartant

回答

6

您可以在行動中訪問有效載荷:

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

或者你可以使用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)) 
} 
+0

太棒了。不知何故,我設法錯過了API文檔:https://github.com/ngrx/effects/blob/master/docs/api.md編寫代碼太遲了。十分感謝你的幫助! – Brandon