You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase中更新用户信息及实现登录后分数更新功能

嘿,我来帮你搞定这两个问题!先从Firebase更新用户信息说起,再结合你给的表单代码讲排行榜的分数更新逻辑~

一、Firebase中更新用户信息的方法

Firebase里更新用户信息分两种场景:更新认证核心信息(比如邮箱、密码),和更新自定义用户数据(比如存在Firestore/Realtime Database里的分数、昵称等)。

1. 更新认证核心信息

如果要修改用户的邮箱、密码这类Auth自带的字段,直接用Firebase Auth的API:

// 获取当前登录用户
const currentUser = firebase.auth().currentUser;

if (currentUser) {
  // 更新邮箱
  currentUser.updateEmail("new-email@example.com")
    .then(() => alert("邮箱更新成功"))
    .catch(err => console.error("更新失败:", err));

  // 更新密码(注意:用户需最近登录过,否则会触发重新认证)
  currentUser.updatePassword("newStrongPassword123")
    .then(() => alert("密码更新成功"))
    .catch(err => console.error("更新失败:", err));
}

2. 更新自定义用户数据(比如分数)

大部分场景下,我们会把用户的分数、昵称等存在Firestore或Realtime Database里,以Firestore为例:
假设你有个users集合,每个文档ID对应用户的UID:

const currentUser = firebase.auth().currentUser;

if (currentUser) {
  firebase.firestore().collection("users").doc(currentUser.uid)
    .update({
      score: 150, // 这里替换成表单输入的分数
      lastUpdated: firebase.firestore.FieldValue.serverTimestamp() // 记录更新时间
    })
    .then(() => alert("用户信息更新成功"))
    .catch(err => console.error("更新失败:", err));
}
二、结合你的AngularJS表单实现排行榜分数更新

从你给出的代码来看,这是AngularJS的表单(ng-submit、ng-model这些指令),我帮你完善整个实现流程:

1. 控制器里实现update()提交方法

在你的AngularJS控制器中,结合Firebase写提交逻辑:

app.controller('ScoreUpdateController', function($scope, $firebaseAuth, $firebaseFirestore) {
  // 初始化Firebase实例
  const auth = $firebaseAuth();
  const firestore = $firebaseFirestore();

  // 监听用户登录状态,自动获取当前用户信息
  auth.$onAuthStateChanged(user => {
    if (user) {
      $scope.currentUser = user;
      // 可选:加载用户当前分数到表单
      firestore.collection('users').doc(user.uid).get()
        .then(doc => {
          if (doc.exists) $scope.user.score = doc.data().score;
        });
    } else {
      alert("请先登录再更新分数!");
    }
  });

  // 表单提交的核心方法
  $scope.update = function() {
    // 表单验证不通过直接返回
    if (!$scope.myform.$valid) return;

    const user = auth.$getAuth();
    if (!user) return;

    // 提交分数到Firebase
    firestore.collection('users').doc(user.uid)
      .update({
        score: parseInt($scope.user.score), // 转成数字类型,避免字符串排序问题
        lastUpdated: firebase.firestore.FieldValue.serverTimestamp()
      })
      .then(() => {
        alert("分数更新成功!");
        // 重置表单状态
        $scope.user.score = '';
        $scope.myform.$setPristine();
      })
      .catch(err => {
        console.error("更新失败:", err);
        alert("更新失败,请重试");
      });
  };
});

2. 完善你的表单代码(补全缺失部分)

我帮你补全表单的验证逻辑和提交按钮,确保用户体验更流畅:

<section class="card register">
  <form name="myform" ng-submit="update()" novalidate>
    <div class="textintro">
      <h1>Update Score</h1>
    </div>
    <fieldset>
      <!-- 改成number类型更适合分数输入,加min限制避免负数 -->
      <input type="number" name="score" placeholder="Score" 
             ng-model="user.score" ng-required="true" min="0">
      
      <!-- 验证错误提示 -->
      <p class="error validationerror" 
         ng-show="myform.score.$error.required && myform.score.$touched">
        分数不能为空!
      </p>
      <p class="error validationerror" 
         ng-show="myform.score.$error.min && myform.score.$touched">
        分数不能为负数!
      </p>

      <!-- 表单无效时按钮禁用 -->
      <button type="submit" ng-disabled="myform.$invalid">更新分数</button>
    </fieldset>
  </form>
</section>

3. 排行榜数据展示(可选)

如果要做排行榜展示,从Firestore按分数降序查询即可:

// 在控制器中添加获取排行榜的方法
$scope.loadLeaderboard = function() {
  firestore.collection('users')
    .orderBy('score', 'desc') // 按分数降序排列
    .limit(10) // 只取前10名
    .onSnapshot(querySnapshot => {
      $scope.leaderboard = [];
      querySnapshot.forEach(doc => {
        $scope.leaderboard.push({
          nickname: doc.data().nickname || '匿名用户',
          score: doc.data().score
        });
      });
      $scope.$apply(); // AngularJS需要手动触发视图更新
    });
};

// 页面加载时调用
$scope.loadLeaderboard();

然后在HTML中渲染:

<div class="leaderboard">
  <h2>排行榜Top10</h2>
  <ul>
    <li ng-repeat="item in leaderboard track by $index">
      {{$index + 1}}. {{item.nickname}} - {{item.score}}分
    </li>
  </ul>
</div>

小提示

  • 一定要检查用户登录状态,避免未登录用户提交数据;
  • 分数存数字类型,这样排序和计算才不会出问题;
  • 如果用Realtime Database,写法类似,只是API换成firebase.database().ref('users/' + user.uid).update({score: ...})。

内容的提问来源于stack exchange,提问作者Anish Joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:56:03