0

I am new to learning angular and having trouble understand some of the basics.

I have my controller line shown below:

   $scope.test =  fileLoader.loadFile();

And my factory service shown below:

angular.module('myWellnessTrackerApp')
  .factory('fileLoader', function($http) {

    return{
      loadfile : function(fileLoc){
        $http.get('data/sideEffects.json').success(function(data) {
          // you can do some processing here
          return data;
        });
      }
    };

  });

Which throws an error. But when my controller line is

   $scope.test =  fileLoader.data;

And my service is

angular.module('myWellnessTrackerApp')
  .factory('fileLoader', function($http) {

    var obj = {content:null};


    $http.get('data/sideEffects.json').success(function(data) {
      // you can do some processing here
      obj.content = data;
    });

    return obj;
  });

Which i don't understand and I would like to be able to understand how to make services in particularly a HTTP service wrapper for requesting a page or local file and having it returned.

Thanks

1 Answer 1

2

You can't just do

$scope.test =  fileLoader.loadFile();

loadFile is an async call, and you can't return from that! You can use .then to continue the promise pattern. Your factory would change to:

loadFile : function(fileLoc){
    return $http.get('data/sideEffects.json').then(function(result) {
        // you can do some processing here
        return result.data;
    });
}

And your controller:

fileLoader.loadFile().then(function(data) {
    $scope.test = data;
});
Sign up to request clarification or add additional context in comments.

5 Comments

That still causes issues for me "undefined is not a function"
fileLoader.loadFile().then(function(data) {
@LmC -- Alright, now give it a go - loadFile was improperly cased in my example.
I must say you are a star, Do you have any recommend pages for reading with regards to services, good practices and angular?
@LmC -- This article is pretty helpful: tylermcginnis.com/angularjs-factory-vs-service-vs-provider

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.