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

AngularJS通过HTTP Get拉取用户列表后循环校验登录密码失效问题

问题根因

你的代码核心错误是在登录校验函数中没有通过$scope访问用户列表数组:你在接口请求成功后把用户列表存到了$scope.userList中,但loginValidator方法内直接写userList.length、userList[i],相当于从全局作用域查找userList变量,这个变量根本不存在,所以逻辑直接报错中断,无法正常返回登录结果。

修正方案

只需要修改loginValidator方法的代码即可,同时可以增加加载状态判断,避免接口还未返回时用户点击登录触发报错,修正后的代码如下:

$scope.loginValidator = function() {
  // 兼容用户数据未加载完成的场景
  if (!$scope.userList) {
    $scope.feedback = '用户数据加载中,请稍后再试';
    return false;
  }
  // 替换所有userList为$scope.userList
  for(var i = 0; i < $scope.userList.length; i++) {
    if ($scope.usernameInput == $scope.userList[i].LoginName && $scope.passwordInput == $scope.userList[i].Password) {
      $scope.feedback = '登录成功';
      return true;
    }
  }
  $scope.feedback = '登录失败';
};

额外优化建议

你现在用的是提交按钮的ng-click绑定校验逻辑,也可以给<form>标签加ng-submit="loginValidator()"绑定,然后把按钮的type改成button或者阻止表单默认提交行为,避免部分场景下页面自动刷新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:06:03