diff --git a/src/app/auth/auth.effects.ts b/src/app/auth/auth.effects.ts index 9304992..c2d461e 100644 --- a/src/app/auth/auth.effects.ts +++ b/src/app/auth/auth.effects.ts @@ -1,6 +1,38 @@ import { Injectable } from "@angular/core"; import { createEffect, Actions, ofType } from "@ngrx/effects"; -import {} from "rxjs"; -import {} from "rxjs/operators"; +import { of } from "rxjs"; +import { map, concatMap, catchError, tap } from "rxjs/operators"; import { AuthService } from "../shared/services/auth.service"; import { AuthApiActions, AuthUserActions } from "./actions"; + +@Injectable() +export class AuthEffects { + constructor(private actions$: Actions, private auth: AuthService) {} + + getAuthStatus$ = createEffect(() => + this.auth + .getStatus() + .pipe(map(userOrNull => AuthApiActions.getAuthStatusSuccess(userOrNull))) + ); + + login$ = createEffect(() => + this.actions$.pipe( + ofType(AuthUserActions.login), + concatMap(action => { + return this.auth.login(action.username, action.password).pipe( + map(user => AuthApiActions.loginSuccess(user)), + catchError(reason => of(AuthApiActions.loginFailure(reason))) + ); + }) + ) + ); + + logout$ = createEffect( + () => + this.actions$.pipe( + ofType(AuthUserActions.logout), + tap(() => this.auth.logout()) + ), + { dispatch: false } + ); +} diff --git a/src/app/auth/auth.module.ts b/src/app/auth/auth.module.ts index 9936656..2a505c6 100644 --- a/src/app/auth/auth.module.ts +++ b/src/app/auth/auth.module.ts @@ -2,8 +2,10 @@ import { NgModule } from "@angular/core"; import { EffectsModule } from "@ngrx/effects"; import { LoginPageComponentModule } from "./components/login-page"; import { UserComponentModule } from "./components/user"; +import { AuthEffects } from "./auth.effects"; @NgModule({ + imports: [EffectsModule.forFeature([AuthEffects])], exports: [LoginPageComponentModule, UserComponentModule] }) export class AuthModule {}