|
| 1 | +import { NavPushAction } from './../actions/nav.actions'; |
| 2 | +import { Action } from '@ngrx/store'; |
| 3 | +import { AuthActionTypes, LoginCompletedAction, LogoutCompletedAction, SignUpCompletedAction, AuthErrorAction } from './../actions/auth.actions'; |
| 4 | +import { AuthProvider } from './../../providers/auth/auth'; |
| 5 | +import { Observable } from 'rxjs/Observable'; |
| 6 | +import { Injectable } from '@angular/core'; |
| 7 | +import { Actions, Effect } from '@ngrx/effects'; |
| 8 | +import 'rxjs/add/operator/map'; |
| 9 | +import 'rxjs/add/operator/mergeMap'; |
| 10 | +import 'rxjs/add/operator/switchMap'; |
| 11 | +import 'rxjs/add/operator/do'; |
| 12 | +import 'rxjs/add/operator/catch'; |
| 13 | +import 'rxjs/add/observable/of'; |
| 14 | +import 'rxjs/add/observable/from'; |
| 15 | + |
| 16 | + |
| 17 | +@Injectable() |
| 18 | +export class AuthEffects { |
| 19 | + |
| 20 | + constructor( |
| 21 | + private authService: AuthProvider, |
| 22 | + private actions$: Actions |
| 23 | + ) { } |
| 24 | + |
| 25 | + @Effect() |
| 26 | + loginAction$: Observable<Action> = this.actions$ |
| 27 | + .ofType(AuthActionTypes.LOGIN_REQUESTED) |
| 28 | + .map(this.toPayload) |
| 29 | + .switchMap(payload => this.authService.signIn(payload) |
| 30 | + .mergeMap(res => Observable.from([ |
| 31 | + (new LoginCompletedAction({user: res})), |
| 32 | + (new NavPushAction({page: 'HomePage', toRootNav: true})) |
| 33 | + ])) |
| 34 | + .catch(this.handleError) |
| 35 | + ); |
| 36 | + |
| 37 | + @Effect() |
| 38 | + logoutAction$: Observable<Action> = this.actions$ |
| 39 | + .ofType(AuthActionTypes.LOGOUT_REQUESTED) |
| 40 | + .map(this.toPayload) |
| 41 | + .switchMap(payload => this.authService.signOut() |
| 42 | + .map(res => (new LogoutCompletedAction())) |
| 43 | + .catch(this.handleError) |
| 44 | + ); |
| 45 | + |
| 46 | + @Effect() |
| 47 | + signUpAction$: Observable<Action> = this.actions$ |
| 48 | + .ofType(AuthActionTypes.SIGNUP_REQUESTED) |
| 49 | + .map(this.toPayload) |
| 50 | + .switchMap(payload => this.authService.signUp(payload.user) |
| 51 | + .map(res => (new SignUpCompletedAction({user: res}))) |
| 52 | + .catch(this.handleError) |
| 53 | + ); |
| 54 | + |
| 55 | + private handleError(error) { |
| 56 | + return Observable.of(new AuthErrorAction({error: error})); |
| 57 | + } |
| 58 | + |
| 59 | + private toPayload(action){ |
| 60 | + return action.payload; |
| 61 | + } |
| 62 | +} |
0 commit comments