来自静态文件的Angular用户JSON请求

时间:2017-03-24 15:01:08

标签: javascript jquery angularjs json

我目前正在尝试实现此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文件的用户名和密码,而不是静态的   字符串?

5 个答案:

答案 0 :(得分:1)

检查这个例子:

.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

答案 1 :(得分:1)

  

部分摘录来自http://jasonwatmore.com/post/2014/05/26/angularjs-basic-http-authentication-example

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

我改变了什么?

原始登录代码段为:

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

答案 2 :(得分:0)

我不完全确定为什么$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
});

答案 3 :(得分:0)

查看示例,您是否尝试在Service方法中放置用于读取json文件的函数。如果你这样做,那么就没有可用的范围。因此,你得到低于错误

ReferenceError: $scope is not defined

在您的代码中,定义了局部变量详细信息但未初始化。因此它的价值是不确定的。

  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文件的用户名和密码,而不是静态的   字符串?

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

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

答案 4 :(得分:0)

根据以下错误进行观察

<强> 1。 ReferenceError:$ scope未定义

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

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

<强> 2。 TypeError:无法读取属性&#39;用户名&#39;未定义的

  • 代码中的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);        
}]);