Advertisement
Guest User

Untitled

a guest
Aug 27th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. auth.effects.ts
  2. import { Injectable } from '@angular/core';
  3. import { Actions, Effect } from '@ngrx/effects';
  4. import { Router } from '@angular/router';
  5. import 'rxjs/add/operator/map';
  6. import 'rxjs/add/operator/do';
  7. import 'rxjs/add/operator/switchMap';
  8. import 'rxjs/add/operator/mergeMap';
  9. import { fromPromise } from 'rxjs/observable/fromPromise';
  10. import * as firebase from 'firebase';
  11.  
  12. import * as AuthActions from './auth.actions';
  13.  
  14. @Injectable()
  15. export class AuthEffects {
  16. @Effect()
  17. authSignup = this.actions$
  18. .ofType(AuthActions.TRY_SIGNUP)
  19. .map((action: AuthActions.TrySignup) => {
  20. return action.payload;
  21. })
  22. .switchMap((authData: {username: string, password: string}) => {
  23. return fromPromise(firebase.auth().createUserWithEmailAndPassword(authData.username, authData.password));
  24. })
  25. .switchMap(() => {
  26. return fromPromise(firebase.auth().currentUser.getIdToken());
  27. })
  28. .mergeMap((token: string) => {
  29. return [
  30. {
  31. type: AuthActions.SIGNUP
  32. },
  33. {
  34. type: AuthActions.SET_TOKEN,
  35. payload: token
  36. }
  37. ];
  38. });
  39.  
  40. @Effect()
  41. authSignin = this.actions$
  42. .ofType(AuthActions.TRY_SIGNIN)
  43. .map((action: AuthActions.TrySignup) => {
  44. return action.payload;
  45. })
  46. .switchMap((authData: {username: string, password: string}) => {
  47. return fromPromise(firebase.auth().signInWithEmailAndPassword(authData.username, authData.password));
  48. })
  49. .switchMap(() => {
  50. return fromPromise(firebase.auth().currentUser.getIdToken());
  51. })
  52. .mergeMap((token: string) => {
  53. this.router.navigate(['/']);
  54. return [
  55. {
  56. type: AuthActions.SIGNIN
  57. },
  58. {
  59. type: AuthActions.SET_TOKEN,
  60. payload: token
  61. }
  62. ];
  63. });
  64.  
  65. @Effect({dispatch: false})
  66. authLogout = this.actions$
  67. .ofType(AuthActions.LOGOUT)
  68. .do(() => {
  69. this.router.navigate(['/']);
  70. });
  71.  
  72. constructor(private actions$: Actions, private router: Router) {
  73. }
  74. }
  75. app.module.ts
  76. EffectsModule.forRoot([AuthEffects])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement