[英]angularjs strange array behaviour, probably related to asynchronous execution?
Difficult to reproduce, so I will try to explain instead. 难以复制,因此我将尝试解释一下。
Within a factory of angularjs I have a function like this 在angularjs的工厂中,我有一个像这样的函数
angular.module('my').factory('Database', ['$window', 'Raw', function($window, Raw) {
return {
read: function() {
where Raw is another factory defined below that returns a data string 其中Raw是下面定义的另一个工厂,该工厂返回数据字符串
Then I do this: 然后我这样做:
var lines = [];
lines = Raw.data.split("*");
which gives me an array of strings. 这给了我一个字符串数组。
The strange behaviour is that it gives an error as lines[0] is undefined. 奇怪的行为是由于未定义lines [0],因此会产生错误。 I can solve this error by adding an alert
我可以通过添加警报来解决此错误
var lines = [];
lines = Raw.data.split("*");
alert(lines[0])
which shows me the expected string. 这向我显示了预期的字符串。 But it does not work if I put a console.log command instead.
但是,如果我改用console.log命令,它将无法正常工作。
So, what's going on?? 发生什么了??
Cheers, 干杯,
Sounds like you get Raw.data
by async way and when you try split it, it still undefined
. 听起来您
Raw.data
通过异步方式获取Raw.data
的,当您尝试拆分它时,它仍然是undefined
。
If Raw.data
returns promise, use then()
callback than, something like: 如果
Raw.data
返回Raw.data
,请使用then()
回调,例如:
var myModule = angular.module('myModule', []);
myModule.controller('myController', ['$scope', 'Database', function($scope, Database) {
$scope.text = Database.read();
}]);
myModule.factory('Database', ['$window', 'Raw', '$q', function($window, Raw, $q) {
return {
read: function() {
var deferred=$q.defer();
Raw.data().then(function(data) {
lines = data.split("*");
deferred.resolve(lines);
});
return deferred.promise;
}
}
}]);
myModule.factory('Raw', ['$window', '$q', function($window, $q) {
return {
data: function() {
var data = "blah * blah";
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.