1

Difficult to reproduce, so I will try to explain instead.

Within a factory of angularjs I have a function like this

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

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. 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.

So, what's going on??

Cheers,

1
  • please post Raw.data code Commented Feb 12, 2014 at 10:53

1 Answer 1

1

Sounds like you get Raw.data by async way and when you try split it, it still undefined.

If Raw.data returns promise, use then() callback than, something like:

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;
        }
    }
}]);

Demo Fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

I didn't know about promises, very interesting (thanks). Then, Raw is a factory that returns the string "data". In order to make it to return a promise, should I make a function then? Or is there any other way?
please post the data structure and ill post Fiddle example how it should work with promises
Thanks a lot! And I see that you add a 2nd promise because you cannot leave a factory without a return value, so if you want to return what is inside the "then" function, then you need a promise. Much clearer now, thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.