Chrillewoodz Chrillewoodz - 1 month ago 12
TypeScript Question

Angular 2 effect is not working

Reducer:

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
});
}
}


Effect:

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
}


And in component in
ngOnInit
I call this:

this.store.dispatch({type: GET_BRANDS});


And the error that is thrown is
Uncaught (in promise): TypeError: unknown type returned
, I'm guessing that this is because I haven't defined it in the reducer. But I don't want to define
GET_BRANDS
in the reducer as it won't do anything to my state, I just want to have
SET
methods in my reducer to set the data I get from the api.

I'm not sure if this is the correct way of doing it though, can someone shed some light on this?

EDIT:

I tried to add a
GET_BRANDS
action to the reducer which just set some
isBusy
state to
true
but it gives me the same error so I'm not sure what is the issue..

I also looked at this question which suggests switching
switchMapTo
to
switchMap
but I'm already using
switchMap
..

Answer

use it with:

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

You don't need to use store.dispatch.

Did you imported SET_BRANDS from actions in your BrandsEffects? It seams not.