sliceofbytes
4/19/2018 - 9:15 PM

Is this stupid?

Is this stupid?

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 group from '../actions/group';
import { CourseService, Group, TreeItem } from '../../shared';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/startWith';

@Injectable()
export class GroupEffects {

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

  @Effect()
  groupsLoadAll$: Observable<Action> = this.actions$
    .ofType(group.GROUP_LOAD_ALL)
    .startWith(new group.GroupLoadAllAction)
    .switchMap(() => {
      return this.service.getGroups()
          .map((gvms: TreeItem<Group>[]) => {
            var flat = new Array<Group>();
            var flatten = (g: TreeItem<Group>, depth: number) => {
              flat.push(new Group(g.item.id, g.item.name, depth));
              if (g.children && g.children.length) {
                depth++;
                for (let i = 0; i < g.children.length; i++) {
                  flatten(g.children[i], depth);
                }
              }
            };
            for (let j = 0; j < gvms.length; j++) {
              flatten(gvms[j],0);  
            }
            return new group.GroupLoadAllSuccessAction({ groups: gvms, flat:flat, error: undefined, loading: false });
          })
         .catch((error: Error) => of(new group.GroupLoadAllFailAction({ error: error, loading: false })));
    });
}