angular6ngrxngrx-effects

How to pass params (action.payload) to service in ngrx/effects ?


I am new to ngrx-6. The effects will listen to action "LOAD_COURSE_DETAILS" and should make a call to service with the course_id (action.payload). But i am getting an error

Property 'toFixed' is missing in type 'Action'.

However, if I do console.log, I could see the data being passed from the component to the effects.

add params to effects

How to pass the parameters to the service?

Thanks in advance.


file: effects

@Effect()
loadCourseDetails$ = this.actions$.pipe(
  ofType(CourseActionTypes.LOAD_COURSE_DETAILS),
  switchMap((action) => {
    console.log('in course effects', action);
    return this.courseService.getCourseDetails(action).pipe(
      map((data) => new fromCourse.LoadCourseDetailsSuccess(data))
    );
  })
);

file: actions.ts (my action has payload defined)

export class LoadCourseDetails implements Action {
  readonly type = CourseActionTypes.LOAD_COURSE_DETAILS;
  constructor(public payload: Number) {}
}
export class LoadCourseDetailsSuccess implements Action {
  readonly type = CourseActionTypes.LOAD_COURSE_DETAILS_SUCCESS;
  constructor(public payload: ICourse) {}
}

file: component.ts (dispatch action)

loadCourseDetails(id: Number) {
  console.log('dispatch course id', id);
  this.store.dispatch(new fromCourse.LoadCourseDetails(id));
}

file: service.ts (to be called by effeccts)

getCourseDetails(courseId: Number) {
    return this.http.get(`url/${courseId}.json`);
}


Solution

  • You have to use the payload from the action. In order to do this you'll have to fill in the generic of the ofType function.

    Now the action inside switchMap is smart enough to know it's a LoadCourseDetails action, and thus will also known the payload type.

    @Effect()
    loadCourseDetails$ = this.actions$.pipe(
      ofType<LoadCourseDetails>(CourseActionTypes.LOAD_COURSE_DETAILS),
      switchMap((action) => {
        console.log('in course effects', action);
        return this.courseService.getCourseDetails(action.payload).pipe(
          map((data) => new fromCourse.LoadCourseDetailsSuccess(data))
        );
      })
    );
    

    For more effect usages, check out Start using ngrx/effects for this