Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { Observable } from 'rxjs/Observable';
- import { AngularFireAuth } from 'angularfire2/auth';
- import * as firebase from 'firebase/app';
- @Injectable()
- export class AuthService {
- user: Observable<firebase.User>;
- private userData = {
- uid: null,
- email: null,
- displayName: null
- };
- constructor(private firebaseAuth: AngularFireAuth) {
- this.user = firebaseAuth.authState;
- }
- signup(email: string, password: string, displayName: string) {
- const authC = this;
- this.firebaseAuth
- .auth
- .createUserWithEmailAndPassword(email, password)
- .then(value => {
- console.log('Success!', value);
- authC.userData.uid = value.uid;
- authC.userData.email = email;
- value.updateProfile({
- displayName: displayName
- }).then(() => {
- console.log('Update display name success!');
- authC.userData.displayName = value.displayName;
- authC.setUserDateToLocalStorage(authC.userData);
- }, err2 => {
- console.log('Update display name fail:', err2.message);
- console.log(err2);
- });
- })
- .catch(err => {
- console.log('Something went wrong:' , err.message);
- console.log(err);
- });
- }
- login(email: string, password: string) {
- const authC = this;
- if (email && password) {
- this.firebaseAuth
- .auth
- .signInWithEmailAndPassword(email, password)
- .then(value => {
- setTimeout(() => {
- authC.userData.displayName = value.displayName;
- authC.userData.email = value.email;
- authC.userData.uid = value.uid;
- authC.setUserDateToLocalStorage(authC.userData);
- }, 100);
- })
- .catch(err => {
- console.log('Something went wrong:', err.message);
- console.log(err);
- });
- }
- }
- logout() {
- this.firebaseAuth
- .auth
- .signOut();
- location.pathname = '/login';
- }
- setUserDateToLocalStorage(userData) {
- if (userData) {
- let email;
- email = !userData.email || userData.email === null || userData.email === 'null' ? '' : userData.email;
- localStorage.setItem('displayName', userData.displayName);
- localStorage.setItem('email', email);
- localStorage.setItem('uid', userData.uid);
- return;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement