如何在重新加载API调用中仅从ngrx / store获取最新数据

时间:2019-07-31 14:12:20

标签: angular typescript redux rxjs ngrx

我在我的角度应用程序中使用了ngrx / store和ngrx / effects。

我的问题是,从功能状态进行api调用后,reducer中的选择器会返回旧值和新值。下面是我的代码:

reducer.ts

case PortfolioActions.PortActionTypes.LOAD_SUCCESS_TRADE_NAV:
    return {
        ...state,
        navData: action.payload,
        isLoadingNav: false
    };

export const getNavData = createSelector(
    getPortfolioFeatureState,
    state => state.navData
);

In Effects.ts

@Effect()
    loadNav$: Observable<Action> = this.action$.pipe(
        ofType<fromPortfolio.LoadTradeNAV>(fromPortfolio.PortActionTypes.LOAD_TRADE_NAV),
        switchMap((action) => this.dashSvc.getNetAssetValue(action.payload.key,action.payload.currency)
            .pipe(
                map((data) => {
                    return new fromPortfolio.LoadSuccessTradeNAV(data)
                })
            )
        )
    );

在compoenent.ts

reload(){
    this.portStore.dispatch(new portfolioActions.LoadTradeNAV(this.searchParam));

    this.portStore.pipe(
    select(fromPortfolio.getNavData),
    filter(f => !!f),
    takeWhile(() => this.componentActive))
    .subscribe((fmtRes) => {
        console.log(fmtRes) //Issue here
        this.data = fmtRes;
    })
}

在组件中,当我调用reload()方法时,在subscribe()中,我总是获取旧数据,然后在完成api调用之后获取新数据。

我的问题是,如何仅在api加载成功后才能获取存储数据

1 个答案:

答案 0 :(得分:2)

您可以使用withLatestFrom

@Effect()
    loadNav$: Observable<Action> = this.action$.pipe(
        ofType<fromPortfolio.LoadTradeNAV>(fromPortfolio.PortActionTypes.LOAD_TRADE_NAV),
        withLatestFrom(this.store.pipe(select(selector))), // pass in your selector here in select()
        switchMap((action) => this.dashSvc.getNetAssetValue(action.payload.key,action.payload.currency)
            .pipe(
                map((data) => {
                    return new fromPortfolio.LoadSuccessTradeNAV(data)
                })
            )
        )
    );

更新。我建议您将这段代码放在ngOnInit()钩子中

ngOnInit() {
    this.portStore.pipe(
    select(fromPortfolio.getNavData),
    filter(f => !!f),
    takeWhile(() => this.componentActive))
    .subscribe((fmtRes) => {
        console.log(fmtRes) //Issue here
        this.data = fmtRes;
    })
}