Advertisement
thepriefy

Angular Service Example

Aug 23rd, 2017
1,575
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import { Injectable } from '@angular/core';
  2. import { Observable } from 'rxjs/Observable';
  3.  
  4. import { AngularFireAuth } from 'angularfire2/auth';
  5. import * as firebase from 'firebase/app';
  6.  
  7. @Injectable()
  8. export class AuthService {
  9. user: Observable<firebase.User>;
  10. private userData = {
  11. uid: null,
  12. email: null,
  13. displayName: null
  14. };
  15.  
  16. constructor(private firebaseAuth: AngularFireAuth) {
  17. this.user = firebaseAuth.authState;
  18. }
  19.  
  20. signup(email: string, password: string, displayName: string) {
  21. const authC = this;
  22. this.firebaseAuth
  23. .auth
  24. .createUserWithEmailAndPassword(email, password)
  25. .then(value => {
  26. console.log('Success!', value);
  27. authC.userData.uid = value.uid;
  28. authC.userData.email = email;
  29.  
  30. value.updateProfile({
  31. displayName: displayName
  32. }).then(() => {
  33. console.log('Update display name success!');
  34. authC.userData.displayName = value.displayName;
  35. authC.setUserDateToLocalStorage(authC.userData);
  36. }, err2 => {
  37. console.log('Update display name fail:', err2.message);
  38. console.log(err2);
  39. });
  40. })
  41. .catch(err => {
  42. console.log('Something went wrong:' , err.message);
  43. console.log(err);
  44. });
  45. }
  46.  
  47. login(email: string, password: string) {
  48. const authC = this;
  49. if (email && password) {
  50. this.firebaseAuth
  51. .auth
  52. .signInWithEmailAndPassword(email, password)
  53. .then(value => {
  54. setTimeout(() => {
  55. authC.userData.displayName = value.displayName;
  56. authC.userData.email = value.email;
  57. authC.userData.uid = value.uid;
  58. authC.setUserDateToLocalStorage(authC.userData);
  59. }, 100);
  60. })
  61. .catch(err => {
  62. console.log('Something went wrong:', err.message);
  63. console.log(err);
  64. });
  65. }
  66. }
  67.  
  68. logout() {
  69. this.firebaseAuth
  70. .auth
  71. .signOut();
  72. location.pathname = '/login';
  73. }
  74.  
  75. setUserDateToLocalStorage(userData) {
  76. if (userData) {
  77. let email;
  78. email = !userData.email || userData.email === null || userData.email === 'null' ? '' : userData.email;
  79. localStorage.setItem('displayName', userData.displayName);
  80. localStorage.setItem('email', email);
  81. localStorage.setItem('uid', userData.uid);
  82. return;
  83. }
  84. }
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement