如何订阅ngRx状态

时间:2019-05-11 14:19:22

标签: javascript angular firebase ngrx ngrx-store

我目前正在设置ngrx应用。目标之一是即使应用程序太小,也要使用ngrx进行自我训练。

这是一个用于啤酒库存管理的小项目。

我有一个要在其中显示啤酒清单的组件:

export class BeerListComponent implements OnInit {

    availableBeers$: Beer[];
    constructor(private breadcrumbService: BreadcrumbService,
        private beerService: BeersService,
        private store: Store<fromBeer.BeerState>) {
        this.breadcrumbService.setItems([
            { label: 'Beers' },
            { label: 'List' }
        ]);
    }

    ngOnInit() {
        this.store.select(fromBeer.getAvailableBeers).subscribe((beers: Beer[]) => {
            console.log(beers);
            this.availableBeers$ = beers;
        })
        console.log('fetching beers');
        this.beerService.fetchBeersList();
    }
}

我的啤酒服务执行以下操作:

export class BeersService {
    private firebaseSubscription: Subscription[] = [];

    constructor(
        private db: AngularFirestore,
        private store: Store<fromBeers.BeerState>) { }


    fetchBeersList() {
        this.firebaseSubscription.push(this.db
            .collection('beers')
            .valueChanges()
            .subscribe((beers: Beer[]) => {
                console.log("Received a firebase change");
                console.log(beers);
                this.store.dispatch(new SetAvailableBeers(beers));
            }, error => {
                console.log(error);
            }));
    }
}

这是我的减速器/动作:

操作

export enum BeersActionTypes {
    SET_AVAILABLE_BEERS = '[Beers] SET_AVAILABLE_BEERS'
};


export class SetAvailableBeers implements Action {
    readonly type = BeersActionTypes.SET_AVAILABLE_BEERS;

    constructor(public payload: Beer[]) {
        console.log(payload);
    }
}

export type BeersActions
                        = SetAvailableBeers;

减速器

export interface BeerState {
    availableBeers: Beer[];
};

const initialState: BeerState = {
    availableBeers: []
};

export function beersReducer(state = initialState, action: BeersActions): BeerState {
    switch (action.type) {
        case BeersActionTypes.SET_AVAILABLE_BEERS: {
            console.log("Setting available beerse")
            return {
                ...state,
                availableBeers: action.payload
            };
        }

        default: {
            return state;
        }
    }
}


export const getAvailableBeers = (state: BeerState) => state.availableBeers;

我不明白的地方:

我从firebase那里收到了啤酒,但是我的组件从未获得更新。如果我检查chrome开发工具,我只会得到一个undefined,但此后不会更新。

这是我的日志: enter image description here

我觉得我没有正确注册到ngrx状态,但是我无法弄清楚自己做错了什么?

1 个答案:

答案 0 :(得分:0)

我想我发现了我的错误!

我直接订阅beerReducers.getAvailableBeers,而不是我的app.reducer(包含CreateSelector和东西)之一