import { Injectable } from '@angular/core' ; import { Effect , Actions , ofType } from '@ngrx/effects' ; import { Store } from '@ngrx/store' ; import { switchMap , map , filter , take , mergeMap } from 'rxjs/operators' ; import { empty } from 'rxjs' ; import { QuestionService } from 'shared-library/core/services' ; import { Question , RouterStateUrl } from 'shared-library/shared/model' ; import { UserActionTypes } from '../actions' ; import * as userActions from '../actions/user.actions' ; import { AppState } from '../../../store' ; import { coreState } from 'shared-library/core/store' ; import { ROUTER_NAVIGATION } from '@ngrx/router-store' ; @ Injectable ( ) export class UserEffects { @ Effect ( ) loadUserPublishedRouteQuestions$ = this . actions$ . pipe ( ofType ( ROUTER_NAVIGATION ) ) . pipe ( map ( ( action ) : RouterStateUrl => action . payload . routerState ) , filter ( ( routerState ) => routerState . url . toLowerCase ( ) . startsWith ( '/user/my/questions' ) ) , mergeMap ( ( routerState ) => this . store . select ( coreState ) . pipe ( map ( s => s . user ) , filter ( u => ! ! u ) , take ( 1 ) , map ( user => user . userId ) ) ) ) . pipe ( switchMap ( ( id ) => { return this . questionService . getUserQuestions ( id , true ) . pipe ( map ( ( questions ) => new userActions . LoadUserPublishedQuestionsSuccess ( questions ) ) ) ; } ) ) ; @ Effect ( ) loadUserUnpublishedQuestions$ = this . actions$ . pipe ( ofType ( ROUTER_NAVIGATION ) ) . pipe ( map ( ( action ) : RouterStateUrl => action . payload . routerState ) , filter ( ( routerState ) => routerState . url . toLowerCase ( ) . startsWith ( '/user/my/questions' ) ) , mergeMap ( ( routerState ) => this . store . select ( coreState ) . pipe ( map ( s => s . user ) , filter ( u => ! ! u ) , take ( 1 ) , map ( user => user . userId ) ) ) ) . pipe ( switchMap ( ( id ) => { return this . questionService . getUserQuestions ( id , false ) . pipe ( map ( ( questions ) => new userActions . LoadUserUnpublishedQuestionsSuccess ( questions ) ) ) ; } ) ) ; @ Effect ( ) addQuestion$ = this . actions$ . pipe ( ofType ( UserActionTypes . ADD_QUESTION ) ) . pipe ( switchMap ( ( action ) => { return this . questionService . saveQuestion ( action . payload . question ) ; } ) ) ; constructor ( private actions$ , private questionService , private store ) { } }