Search code examples
htmljsonangularrestjson-server

Making ngrx-effects REST call


I am developing angular REST application using ngrx/effects, I am using example application GIT. I am trying to replace hardcoded json data in effects, from http REST end. I am getting errors "Effect "GetTodoEffects.todo$" dispatched an invalid action" . Could you please help me in solving it. Every thing is same as git code, except effects code which is i am pasting below. Effects code:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime'; 
import 'rxjs/add/operator/withLatestFrom'
import { of } from 'rxjs/observable/of';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Action, Store } from '@ngrx/store';
import { Actions, Effect, toPayload } from '@ngrx/effects';
import * as Act from '../actions/app.actions';
import * as fromStore from '../reducers';

import { HttpClient } from '@angular/common/http';

@Injectable()
export class GetTodoEffects {

@Effect() todo$ = this.actions$.ofType(Act.GET_TODO)
.map(toPayload)
.withLatestFrom(this.store$)
.mergeMap(([ payload, store ]) => {

  return this.http$
    .get(`http://localhost:4000/data/`)
    .map(data => {
      return [
        new Act.GetTodoSuccess({ data: data })
      ]
    })
    .catch((error) => {
      return [
        new Act.GetTodoFailed({ error: error })
      ]
    })
});


 constructor(
  private actions$: Actions,
  private http$: HttpClient,
  private store$: Store<fromStore.State>
) {}
}

I am using json-server as REST end point. json-server --port 4000 --watch expt-results-sample.json

expt-results-sample.json

[
        {
          text: "Todo 1"
        },
        {
          text: "Todo 2"
        },
        {
          text: "Todo 3"
        }
      ]
    })
  ]

Solution

  • First thing I suspect is the array. Try changing it to an observable.

      return this.http$
        .get(`http://localhost:4000/data/`)
        .map(data => {
          // You don't need an array because it's only 1 item
          // If you want array use `Observable.from([ /* actions here */ ])`
          //    but then you'll need to change `map` above to 
          //     `mergeMap` or `switchMap`
          //   (no big difference for this use case,
          //     `switchMap` is more conventional in Ngrx effects)
          return new Act.GetTodoSuccess({ data: data });
        })
        .catch((error) => {
          // You probably haven't called this yet,
          //   but `catch` must return `Obsrvable`
          // Again, if you want an array use `Observable.from([ /* array */ ])`
          return Observable.of(
            new Act.GetTodoFailed({ error: error })
          );
        })