2

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;
        }
    });
})();
0

2 Answers 2

0

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;
});
Sign up to request clarification or add additional context in comments.

Comments

0

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>

6 Comments

1) OP may have created the module elsewhere and is using the module getter angular.module(moduleName)
2) DI annotations are only required when minifying code
Yes may be but that was not visible in the code snippet, so I have inject the dependency array
3) OP is returning the promise from $http
when I run the above code. It's shows " contacts is not defined" @Phil
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.