【发布时间】:2016-05-06 10:22:31
【问题描述】:
我目前正在为大学做最后一年的项目。我正在制作一个 UI,它从数据库中获取数据,然后使用用户输入操作数据以生成图形。
事件的顺序是:DataCtrl 使用 HTTP get 从数据库中获取数据。然后将数据存储在 dataFactory 中。然后 RadioCtrl 将查找用户输入以进行选择。然后将其存储在 userFactory 中。
我想要做的是创建一个函数来比较来自 dataFactory 的数据与来自 userFactory 的输入,但是它不断出现 dataFactory 未定义。我知道我需要实现某种承诺/延迟,但我从来没有使用过,而且我正在学习 Javascript,所以我不太确定如何做到这一点,或者这是否是最好的方法它。我的代码如下,任何问题或建议将不胜感激。
app.factory('dataFactory', function() {
var data = [];
var ids = [];
var areas = [];
var speakers = [];
var nonSpeakers = [];
var notStated = [];
var highestEd = [];
var gender = [];
var labourPop = [];
//Array of functions for data
var dataService = {};
dataService.getData = function(response) {
data.push(response);
response.forEach(function(element){
ids.push(element.id);
areas.push(element.area);
labourPop.push(element.labourPop);
speakers.push(element.irishSpeakers);
nonSpeakers.push(element.nonIrishSpeakers);
notStated.push(element.notStated);
highestEd.push(element.highestEd);
gender.push(element.gender);
})
};
dataService.list = function(){
return data;
}
return dataService;
});
app.factory('userFactory', function (){
var education;
var gender;
var location;
var graph;
//Add user input functions here
var userService = {
};
userService.filter = function(dataFactory) {
dataFactory.ids.forEach(function(element){
if(education ===dataFactory.highestEd[element])
graph.push(dataFactory.data[element]);
})
console.log(dataFactory.ids);
};
return userService;
});
app.controller('GraphCtrl', function(dataFactory, userFactory){
userFactory.filter(dataFactory);
});
app.controller ('DataCtrl', function(dataFactory, $http) {
$http.get("http://localhost:6698/ngdemo/rest/users")
.then(function(response) {
dataFactory.getData(response.data);
})
});
app.controller('RadioCtrl', function(userFactory) {
userFactory.education = {
education : ''
};
userFactory.gender = {
gender : ''
};
userFactory.location = {
location : ''
};
});
【问题讨论】:
-
.then() 中的代码在其他所有内容之后被调用。可能是您的比较代码在 dataFactory.getData(response.data) 之前运行。解决方案是在 dataFactory.getData(response.data) 之后在 .then() 内部开始比较。
标签: javascript angularjs undefined user-input angular-promise