角度2效果不起作用

时间:2016-11-08 08:11:40

标签: angular typescript ngrx

减速机:

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获得的数据

我不确定这是否是正确的做法,有人可以对此有所了解吗?

修改

我尝试向reducer添加GET_BRANDS操作,只将isBusy状态设置为true,但它给了我同样的错误,所以我不确定是什么问题..

我还查看this question建议将switchMapTo切换为switchMap,但我已经在使用switchMap ..

2 个答案:

答案 0 :(得分:2)

使用它:

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

您不需要使用store.dispatch。

您是否从 BrandsEffects 中的操作导入了SET_BRANDS?它不接缝。

答案 1 :(得分:0)

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