Service returning undefined to the controller

By : shanwar
Source: Stackoverflow.com
Question!

This is my service:

'use strict';

    app
    .service('myService', function($http) {

        this.getJSON = function() {
            return $http.get('someUrl/dataForm').then(function(data){
                return data.result;
            });
        };
    });

And in my controller I have:

'use strict'
        app.controller('myController', function ($scope, myService) {

            myService.getJSON().then(function(data){
                $scope.myData =data;
            });
            console.log($scope.myData);
        });

I can see that the http call is successfully returning a JSON value but the console log shows that the value of myData is undefined. What am I doing wrong ?

By : shanwar


Answers
  1. $http.get() returns promise object.
  2. promise object has then(), catch(), finally() methods.
  3. then is called when success, catch when error.

    change your service to,

app.service('myService', function($http) {
  this.getJSON = function() {
    return $http.get('someUrl/dataForm'); //returns promise object
  };
});

and controller to,

app.controller('myController', function($scope, myService) {
  var promise = myService.getJSON();
  //after resolving then method get called
  promise.then(function(data) {
    $scope.myData = data;
    console.log($scope.myData);
  });
});

By : ram1993


Update the code in the controller

'use strict';
app.service('myService', function($http) {
    this.getJSON = function() {
     return $http.get('someUrl/dataForm').then(function(data){
            return data.result;
        });
    };
});

controller

  'use strict'
   app.controller('myController', function ($scope, myService) {
        myService.getJSON().then(function(data){
            $scope.myData =data;
           console.log($scope.myData);
        });
    });
By : GANI


Place the console.log inside

 myService.getJSON().then(function(data){
                $scope.myData =data;
                console.log($scope.myData);
 });

DEMO



This video can help you solving your question :)
By: admin