登录时将文档添加到数据库

问题描述 投票:0回答:1

由于firebase默认不支持向注册用户添加用户名,因此我尝试找到一种方法将用户名及其UserID写入数据库。因此,我尝试将用户名用户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);
  }**

}
html typescript firebase firebase-realtime-database firebase-authentication
1个回答
0
投票

这个例子是通过Redux Actions用React编写的,但是Javascript都是一样的。您想要从注册表单中捕获所有信息,发送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));

};

© www.soinside.com 2019 - 2024. All rights reserved.