我目前正在尝试实现这个 AngularJS 示例 Tutorial Example Login但我没有将用户名和密码存储为字符串,而是尝试从本地文件中提取。
我知道这是一种不好的做法,但这就是我尝试这样做的方式。
在 AngularJS 身份验证服务部分。路径:/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.类型错误:无法读取未定义的属性“用户名”
What is the esiest way to achieve what I am trying to do? Extract the username and password from a json file and not have them as a static string?
最佳答案
Some snippets are from 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"
}]
为什么要 promise ?
由于您使用 json 文件作为 db,因此您应该使用网络加载 json 文件。而且你不需要加载 data.json 因为它不会改变,所以你可以只加载一次。使用 promise.then
确保验证在 $http.get
之后。
如果你想在每次用户提交表单时加载“data.json”,只需将 promise.then
替换为
$http.get("data.json").then(function (response) {
return response.data;
}).then
关于javascript - 来自静态文件的 Angular 用户 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43002814/