减速机:角2的效果是不工作
import {ActionReducer, Action} from '@ngrx/store';
import {SET_BRANDS, SET_BRAND} from './brands.actions';
import {IBrandsStorage} from './brands-storage.interface';
export const BrandsReducer: ActionReducer<any> = (state: IBrandsStorage = {list: [], single: {}}, action: Action) => {
switch(action.type) {
case SET_BRANDS: return Object.assign({}, state, {
list: [...action.payload.data]
});
case SET_BRAND: return Object.assign({}, state, {
single: action.payload.data
});
}
}
效果:
import {Injectable} from '@angular/core';
import {Action, Store} from '@ngrx/store';
import {Actions, Effect} from '@ngrx/effects';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import {GET_BRANDS, GET_BRAND} from './brands.actions';
import {BrandsApi} from 'app/shared/apis';
@Injectable()
export class BrandsEffects {
constructor(private brandsApi: BrandsApi, private store: Store, private actions$: Actions) {}
@Effect() brands$: Observable<Action> = this.actions$
.ofType(GET_BRANDS)
.switchMap(() => this.brandsApi.getBrands())
.map(brands => this.store.dispatch({type: SET_BRANDS, payload: brands}))
// TODO: Add a catch
@Effect() brand$: Observable<Action> = this.actions$
.ofType(GET_BRAND)
.switchMap(() => this.brandsApi.getBrand())
.map(brand => this.store.dispatch({type: SET_BRAND, payload: brand}))
// TODO: Add a catch
}
而在组件中ngOnInit
我称之为:
this.store.dispatch({type: GET_BRANDS});
而引发的错误Uncaught (in promise): TypeError: unknown type returned
,我猜这是因为我没有在reducer中定义它。但我不想在reducer中定义GET_BRANDS
,因为它不会对我的状态做任何事情,我只想在我的reducer中有SET
方法来设置我从api获得的数据。
我不确定这是否是正确的方式,但有人可以对此有所了解吗?
编辑:
我尝试添加GET_BRANDS
行动刚刚设置一些isBusy
状态true
减速,但它给了我同样的错误,所以我不知道什么是问题..
我也看了this question这表明切换到switchMapTo
但switchMap
我已经使用switchMap
..
删除调度也需要,因为我在使用它时在其他减速器中出现奇怪的错误。谢谢! – Chrillewoodz