无法通过ngrx效果正确获取Firebase数据

时间:2019-02-28 20:03:52

标签: firebase redux ngrx ngrx-store ngrx-effects

由于我遇到了严重的麻烦,我第一次寻求您的帮助。 我正在使用ngrx效果从Firebase实时数据库在应用程序初始化上将一些商店商品加载到购物车中。作为有效负载,我获得了整个firebase数据库快照对象,而不仅仅是商店商品本身,因此ngrx存储收到了一个它无法理解的对象,并且应用程序状态不会更改。

请检查照片:当console.logged()时,我看到了所需的确切对象。但是Redux Devtools揭示了真正的交易,我不知道该如何解决。有人可以给我建议吗?非常非常感谢。

效果如下:

@Effect()
getShopItems: Observable<any> = this.actions.pipe(
    ofType(shopActions.GET_ITEMS),
    switchMap(() => {
        return of(this.database.ref('cart').once('value', snap => {
            snap.forEach(childSnap => childSnap.val());
            // snap.forEach(childSnap =>
            // console.log(childSnap.val()));
        }))
            .pipe(
                map((payload) => {
                    return {
                        type: 'GET_ITEMS_SUCCESS',
                        payload: payload
                    };
                }
            ));
    })
);

有问题的动作的reducer功能如下:

case shopActions.GET_ITEMS: {
            return {
                ...state,
                shopItems: [...state.shopItems],
                itemCount: state.shopItems.length
            };
}
case shopActions.GET_ITEMS_SUCCESS: {
            return {
                ...state,
                shopItems: [action.payload],
                itemCount: state.shopItems.length + 1
            };
}

https://imgur.com/a/pDGAwFI

1 个答案:

答案 0 :(得分:0)

使用 from ,而不是 of

import { from } from 'rxjs';

@Effect()
getShopItems: Observable<any> = this.actions.pipe(
    ofType(shopActions.GET_ITEMS),
    switchMap(() => {
        return from(this.database.ref('cart').once('value', snap => {
            snap.forEach(childSnap => childSnap.val());
        }))
            .pipe(
                map((payload) => {
                    return {
                        type: 'GET_ITEMS_SUCCESS',
                        payload: payload
                    };
                }
            ));
    })
);

RxJs 来自-https://www.learnrxjs.io/operators/creation/from.html