2016-11-08 58 views
0

减速机:角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这表明切换到switchMapToswitchMap我已经使用switchMap ..

回答

2

与使用它:

.map(brands => ({type: SET_BRANDS, payload: brands})) 

您不需要使用store.dispatch。

您是否从您的品牌效应中的操作中导入了SET_BRANDS?它不接缝。

+0

删除调度也需要,因为我在使用它时在其他减速器中出现奇怪的错误。谢谢! – Chrillewoodz

0

原来,这是brandsApi这是错误的,因为它没有返回Observable,而是一些测试数据,我有正常的JSON。当我将其更改为实际的请求时,它没有任何问题就通过了switchMap