0

firebase는 기본적으로 등록 된 사용자에게 사용자 이름을 추가하는 것을 지원하지 않기 때문에 사용자 이름과 사용자 ID를 데이터베이스에 쓰는 방법을 찾으려고합니다. 따라서 데이터베이스에 username 사용자 ID 관계를 작성하려고했습니다. 하지만 어떻게 든이 방법을 실행하지 않습니다. 아래 코드를 찾을 수 있습니다.로그인시 데이터베이스에 문서 추가

HTML 템플릿 :

<mat-tab label="Register"> 
<div class="registerContainer"> 
    <mat-form-field> 
    <input #usernameRegister (keyup.enter)="register(usernameRegister.value, emailRegister.value, passwordRegister.value)" matInput placeholder="Enter your username"> 
    </mat-form-field> 
    <br> 
    <mat-form-field> 
    <input #emailRegister (keyup.enter)="register(usernameRegister.value, emailRegister.value, passwordRegister.value)" matInput placeholder="Enter your email"> 
    </mat-form-field> 
    <br> 
    <mat-form-field> 
    <input #passwordRegister (keyup.enter)="register(usernameRegister.value, emailRegister.value, passwordRegister.value.toString())" matInput placeholder="Enter your password" [type]="hide ? 'text' : 'password'"> 
    <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 'visibility_off'}}</mat-icon> 
    </mat-form-field> 
    <br> 
    **<button mat-raised-button color="primary" (click)="register(usernameRegister.value, emailRegister.value, passwordRegister.value)">Register</button>** 
</div> 

등록 작업 :

register(username:string, email: string, password: string):void{ 
if (username.length != 0) { 
    if (email.length != 0) { 
     this.authenticationService.register(username.toString().trim(), email.toString().trim(), password.toString()) 
     .then((user) => { 
      **console.log('database operation'); 
      this.userService.add(user, username) 
      .then(()=>{ 
       console.log('wrote to database.'); 
      }) 
      .catch((error)=>{ 
       console.log('Error writing to database' + error); 
      });** 
      user.sendEmailVerification() 
      .catch((error) => { 
       console.log(error); 
      }); 
      this.authenticationService.logout() 
      .catch((error)=>{ 
       console.log(error); 
      }); 
      this.dialogRef.close(); 
      this.snackBar.open('Registration completed', null, {duration: 1000}); 
     }) 
     .catch((error) => { 
      console.log(error); 
     }) 
    } 
    else { 
    this.snackBar.open('Please enter an email address.', null, {duration: 1000}); 
    } 
} 
else { 
    this.snackBar.open('Please enter an username.', null, {duration: 1000}); 
} 

사용자 모델 :

export class User implements IFirebaseStorable { 
    constructor(
    public uID:string, 
    public username:string) { 
    } 


} 

인증 서비스 :

,
@Injectable() 
export class AuthenticationService { 

    constructor(public afAuth: AngularFireAuth) { } 

    // login with email address 
    // returns: Promise<any> 
    loginWithEmail(email:string, password:string):Promise<any>{ 
    return this.afAuth.auth.signInWithEmailAndPassword(email, password); 
    } 

    // login via facebook account 
    // returns: Promise<any> 
    loginWithFacebook():Promise<any>{ 
    return this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider()); 
    } 

    // login via Github 
    // returns: Promise<any> 
    loginWithGithub():Promise<any>{ 
    return this.afAuth.auth.signInWithPopup(new firebase.auth.GithubAuthProvider()); 
    } 

    // login via google account 
    // returns: Promise<any> 
    loginWithGoogle():Promise<any>{ 
    return this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()); 
    } 

    // login via Twitter 
    // returns: Promise<any> 
    loginWithTwitter():Promise<any>{ 
    return this.afAuth.auth.signInWithPopup(new firebase.auth.TwitterAuthProvider()); 
    } 

    // register method 
    // parameters: Email - string, Password - string 
    // returns: Promise<any> 
    **register(username:string, email: string, password: string):Promise<any>{ 
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password); 
    }** 

    // checks whether a user is signed in or not 
    // returns: Boolean 
    userIsSignedIn():boolean{ 
    return this.afAuth.auth.currentUser != null; 
    } 

    // logout method 
    // returns: Promise<any> 
    logout() : Promise<any> { 
    return this.afAuth.auth.signOut(); 
    } 

    // returns: current user with following properties: 
    // 
    // displayName: string | null; 
    // email: string | null; 
    // phoneNumber: string | null; 
    // photoURL: string | null; 
    // providerId: string; 
    // uid: string; 
    getLoggedInUser():firebase.User{ 
    return this.afAuth.auth.currentUser; 
    } 

    // send user an email to restore the password 
    forgotPassword(email:string):Promise<any>{ 
    return this.afAuth.auth.sendPasswordResetEmail(email); 
    } 
} 

사용자 데이터베이스 작업 서비스는이 예제로 작성

@Injectable() 
export class UserService { 
    private userCollection: AngularFirestoreCollection<User>; 
    user: Observable<User[]>; 

    constructor(private afs: AngularFirestore) { 
    this.userCollection = afs.collection<User>('User'); 
    this.user = this.userCollection.valueChanges(); 
    } 

    **add(user ,username:string):Promise<DocumentReference>{ 
    const uID = user.uid.toString(); 
    const userAdded : User = {uID, username}; 
    return this.userCollection.add(userAdded); 
    }** 

} 

답변

0

는 돌아 오는 동작을 통해 반작용하지만 자바 스크립트는 모두 동일합니다. signupUserWithEmailAndPassword()를 보내고 signupUserWithEmailAndPassword()를 보내고 데이터베이스에이 데이터를 설정하면 .... signupUserWithEmailAndPassword()를 보내고 .... 다음 데이터를 데이터베이스로 설정하고 싶습니다. ....

Oauth를 사용하고 있으므로 모든 버전의 응답을 캡처해야합니다. 그런 다음 사용자 정의 객체를 만들어 데이터베이스에 설정하십시오. 다른 Oauth 클라이언트를 사용할 때 이것은 나를위한 PITA였습니다.

export const signupRequest = (email, password, username) => dispatch => { 
// ******** The signup actions only trigger for first time users, no need to check database ******** 
console.log('RECIEVED USER TO SIGNUP', email, password); 
firebase.auth().createUserWithEmailAndPassword(email, password) 
    .then((authData) => { 
     // ******** Firebase will create a route with whatever KEY is fed to the .set method ******** 
     // ******** We dont actually want this to avoid deep nesting ******** 
     // ******** So we package up our user.account object and .set(account) without any key value pairs ******** 
     let account = {} 
     account.email = email.toLowerCase() 
     account.uid = authData.uid 
     account.username = username 
     firebase.database().ref('users/' + authData.uid).set({ 
      account 
     }).then(() => { 
      // ******** Now we need to grap a snapshot from the DB to validate account creation and update the redux store locally ******** 
      firebase.database().ref('users/' + authData.uid).once('value').then(function (snapshot) { 
       let updatedUser = snapshot.val(); 
       console.log(' FOUND THIS USER FROM THE DB after signup', username); 
      }).then(() => { 
       dispatch(userSet(updatedUser)); 

      }) 
     }) 
    }).catch((err) => console.log(err)); 

}};