sliceofbytes
4/20/2018 - 3:12 PM

Course events

Course events

import { Action } from '@ngrx/store';
import { Effect, Actions } from '@ngrx/effects';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import * as course from '../actions/course';
import { CourseService, Course } from '../../shared';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/startWith';
import { CourseCopyAction } from '../actions/course';

@Injectable()
export class CourseEffects {

  constructor(private actions$: Actions, private service: CourseService) { }

  @Effect()
  courseLoadAll$: Observable<Action> = this.actions$
      .ofType(course.COURSE_LOAD_ALL)
      .startWith(new course.CourseLoadAllAction)
      .switchMap(() => {
        return this.service.getCourses()
          .map((courses) => new course.CourseLoadAllSuccessAction({ courses: courses, error: undefined, loading: false }))
          .catch((error) => of(new course.CourseLoadAllFailAction({ error: error, loading:false})));
    });

  @Effect()
  courseCopy$: Observable<Action> = this.actions$
    .ofType(course.COURSE_COPY)
    .switchMap((action:CourseCopyAction) => {
      return this.service.copyCourse(action.payload.group,action.payload.id,action.payload.name)
        .map((crs: Course) => new course.CourseCopySuccessAction({ course: crs, error: undefined }))
        .catch((error: Error) => of(new course.CourseCopyFailAction({ error: error })));
    });
}