【问题标题】:Angular user JSON request from a static file来自静态文件的 Angular 用户 JSON 请求
【发布时间】:2017-03-24 15:01:07
【问题描述】:

我目前正在尝试实现这个 AngularJS 示例 Tutorial Example Login,但我没有将用户名和密码存储为 字符串,而是尝试从本地文件中提取。

我知道这是一种不好的做法,但我就是这样做的。

在示例中的AngularJS Authentication Service. Path: /modules/authentication/services.js部分中,用户名和密码存储在超时函数中:

$timeout(function(){
var response = { success: username === 'test' && password === 'test' };
  if(!response.success) {
      response.message = 'Username or password is incorrect';
     }
       callback(response);
}, 1000);

但我正在尝试创建一个静态 json 文件,该文件将用户名和密码作为对象保存。我的想法是向文件发出 $http.get 请求并将 json 对象附加到用户名和密码参数,如下所示:

var details;
$http.get("data.json").then(function(response){
$scope.details = response.data;
    console.log(username);
});


$timeout(function () {
var response = { success: username === details.username && password === details.password 
if (!response.success) {
   response.message = 'Username or password is incorrect';
}
 callback(response);
}, 1000);

但我收到两个错误:
1.ReferenceError: $scope is not defined
2.TypeError: Cannot read property 'username' of undefined

实现我想要做的最简单的方法是什么?提取 来自 json 文件的用户名和密码,而不是将它们作为静态文件 字符串?

【问题讨论】:

    标签: javascript jquery angularjs json


    【解决方案1】:

    一些sn-ps来自http://jasonwatmore.com/post/2014/05/26/angularjs-basic-http-authentication-example

    现场演示:http://plnkr.co/edit/WvOwk1?p=preview

    我改变了什么?

    原来的登录sn-p是:

    service.Login = function (username, password, callback) {
        $timeout(function(){
            var response = { success: username === 'test' && password === 'test' };
            if(!response.success) {
                response.message = 'Username or password is incorrect';
            }
            callback(response);
        }, 1000);
    };
    

    我改成:

    var promise = $http.get("data.json").then(function (response) {
        return response.data;
    });
    
    service.Login = function (username, password, callback) {
        promise.then(function (data) {
            var success = data.some(function (user) {
                if (user.username == username && user.password == password) {
                    callback({
                        success: true
                    });
                    return true;
                } else {
                    return false;
                }
            });
            if (!success) {
                callback({
                    success: false,
                    message: 'Username or password is incorrect'
                });
            }
        });
    };
    

    并添加了一个data.json:

    [{
        "username": "test",
        "password": "test"
    }, {
        "username": "test2",
        "password": "test2"
    }]
    

    为什么要承诺?

    由于您使用 json 文件作为 db,您应该使用网络加载 json 文件。而且您不需要加载 data.json,因为它不会更改,因此您只需加载一次即可。使用promise.then确保验证在$http.get之后。

    如果您想在用户每次提交表单时加载“data.json”,只需将promise.then替换为

    $http.get("data.json").then(function (response) {
        return response.data;
    }).then
    

    【讨论】:

    • 这个答案有点无关紧要。 AuthenticationObfuscation 已从示例中删除。我正在寻找示例的精确副本,但使用 json 文件作为 db.
    • @ZombieChowder 所以你希望结果与plnkr.co/edit/H4SVl6?p=preview 相同,对吧?保留所有功能?
    • 是的,但不是使用 username === 'test' && password === 'test' 来存储密码,而是有一个 json 文件,我可以在其中插入更多用户名和密码..
    • @ZombieChowder 好的,我明白了。
    • @ZombieChowder 您想通过手动编辑 json 文件来插入更多用户名和密码,对吧?因为你实际上没有服务器。
    【解决方案2】:

    检查这个例子:

    .controller('NameOfYourController', function($scope, $http,  $timeout) {
        $scope.details = ""; // you can even omit the declaration here 
        $http.get("data.json").then(function(response){
            $scope.details = response.data;
            console.log($scope.details.username); // or response.data.username   
            $timeout(function () {
              // you get to the response obj using: response.data.your_object
              // $timeout logic goes here
            }, 1000);
        });
    });
    

    注意:如果您在服务中,则没有 $scope

    【讨论】:

    • 感谢 Paolo 的努力。这是在工厂内声明的,当我将它移动到控制器时,整个事情都会中断。正如我所说,我正在研究这个例子,如果您需要更多信息Example,请查看它。提前感谢您的帮助。
    【解决方案3】:

    我不完全确定为什么 $scope 在您的示例中未定义。您很可能不会像使用$http$timeout 那样注入它。另一种可能性是您试图在控制器以外的其他东西中使用$scope

    至于您的第二个错误,details 未定义,因为它是在解决 .then() 承诺之后设置的。您可能希望将您的 $timeout 逻辑移动到该代码块中,如下所示:

    var details;
    $http.get("data.json").then(function(response){
        $scope.details = response.data;
        // ADD YOUR $timeout LOGIC HERE SO DETAILS IS NOT UNDEFINED
    });
    

    【讨论】:

    • [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=<div ng-view="" class="ng-scope">copeProvider%20%3C-%20%24scope%20%3C-%20AuthenticationService 这是我在控制器中插入 $scope 时收到的错误消息。我已经试过了。这就是为什么我留下了实际示例的链接。
    • 此错误表明您将$scope 注入服务。你不能在 AngularJS 中做到这一点。尝试将逻辑移至控制器。
    【解决方案4】:

    查看示例,您是否尝试将读取 json 文件的功能放入 Service 方法中。如果您正在这样做,那么服务中没有可用的 $scope。因此你得到以下错误

    ReferenceError: $scope is not defined
    

    在您的代码中,有一个局部变量 details 已定义但未初始化。因此它的值是未定义的。

      var details;
    

    在超时功能中,您尝试访问 details.username

    username === details.username
    

    因此你得到以下错误

    TypeError: Cannot read property 'username' of undefined
    

    但是,如果您想以最简单的方式进行操作,那么只需将代码放入控制器中,如下所示 this plunker。你应该已经创建了 data.json 文件来运行下面的代码。

    'use strict';
    
    angular.module('Authentication')
    
    .controller('LoginController',
        ['$scope', '$rootScope', '$location', 'AuthenticationService','$http','$timeout',
        function ($scope, $rootScope, $location, AuthenticationService,$http,$timeout) {
            // reset login status
            AuthenticationService.ClearCredentials();
             var details;
            $http.get("data.json").then(function(response){
            $scope.details = response.data;
            //alert($scope.details.username);
            });
    
           function Login(username,password,callback){
                $timeout(function(){
                    var response = { success: username === $scope.details.username && password === $scope.details.password };
                    if(!response.success) {
                        response.message = 'Username or password is incorrect';
                    }
                    callback(response);
                }, 1000);
           }
    
            $scope.login = function () {
                $scope.dataLoading = true;
                Login($scope.username, $scope.password, function(response) {
                    if(response.success) {
                        AuthenticationService.SetCredentials($scope.username, $scope.password);
                        $location.path('/');
                    } else {
                        $scope.error = response.message;
                        $scope.dataLoading = false;
                    }
                });
            };
        }]);
    

    但是如果您想使用相同的控制器并更改服务,请通过 @blackmiaool 找到答案,这绝对是完美的。

    实现我想要做的最简单的方法是什么?提取 来自 json 文件的用户名和密码,而不是将它们作为静态文件 字符串?

    第一种方法是最简单的方法,但不是标准做法。

    第二种方法是您尝试做的正确且标准的方法。

    【讨论】:

    • 这个例子是有道理的,但它不起作用。单击登录按钮后应用程序冻结。
    • 您在尝试时一定有错误。我也遇到了同样的错误。请在 plunker 中处理它。我可以在 plunker 中运行它。
    • 请找到这个例子的 plunker 链接。 plnkr.co/edit/RMYguZGwHvVKmA6oXJ5F?p=preview
    【解决方案5】:

    基于以下错误的观察

    1. ReferenceError: $scope 未定义

    • 当我们尝试访问 $scope 对象但忘记将依赖项注入控制器时会出现此错误。

      app.controller('MyCtrl', ['$scope', function ($scope) { ... }
      

    2。类型错误:无法读取未定义的属性“用户名”

    • 您的代码中的username 是什么?
    • 您应该使用$scope.details.username 而不仅仅是username

    您的代码应采用如下格式:

    angular.module('myApp',[]).controller('LoginController',['$scope', function ($scope) {
        var details;
        $http.get("data.json").then(function(response){
            $scope.details = response.data;
            console.log($scope.details.username);
        });
    
        $timeout(function () {
            var response = { success: username === $scope.details.username && password === $scope.details.password 
            if (!response.success) {
                response.message = 'Username or password is incorrect';
            }
            callback(response);
        }, 1000);        
    }]);
    

    【讨论】:

      猜你喜欢
      • 2010-12-18
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多