Angular 2 效果无效

Angular 2 effect is not working

减速器:

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 但它给了我同样的错误所以我不确定是什么问题..

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

将其用于:

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

您不需要使用 store.dispatch。

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

结果是 brandsApi 出了问题,因为它没有 return 和 Observable,而是我正常使用的一些测试数据 JSON.当我将其更改为实际请求时,它顺利通过了 switchMap