Angular JS data response undefined

1.1k views Asked by At

I am new to Angular JS, and am trying to call Rest API using JSON data. When I run HTTP-server , am not getting back my response data.

function contacts(contactsdata) {
    contactsdata.getcontacts().then(function(data) {
        this.contactsinfo = data;
    });
}

(function(){ 
    var mod = angular.module('myapp');
    mod.controller("contacts", contacts);
    mod.service("contactsdata", function($http) {   
        this.getcontacts = function(){
            var execute1 = $http.get('http://localhost:3000/contacts');
            var execute2 = execute1.then(function(response) {
                return response.data;
            })
            return execute2;
        }
    });
})();
2

There are 2 answers

0
Dhananjay C On

You can try this in service

       this.getcontacts = function(){
           return $http.get('http://localhost:3000/contacts');
       });

And use as

contactsdata.getcontacts().then(function(response){
    this.contactsinfo = response.data;
});
6
brk On

There are few issues here.

  1. Need to pass an empty array while initializing angular like this

    var mod = angular.module('myapp', []);

  2. Need to inject the dependency of the service in the controller like this

    mod.controller("contacts", ['$scope', 'contactsdata', contacts]);

  3. You can return the promise from the service like return $http.get... & use the data in the service

function contacts($scope, contactsdata) {
  contactsdata.getcontacts().
  then(function(data) {
    console.log(data)
  });
}


(function() {
  var mod = angular.module('myapp', []);
  mod.controller("contacts", ['$scope', 'contactsdata', contacts]);
  mod.service("contactsdata", ['$http', function($http) {
    this.getcontacts = function() {
      return $http.get('https://jsonplaceholder.typicode.com/posts/1')
    }
  }])

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <div ng-controller="contacts"></div>
</div>