Angularjs $http GET json data not displayed

Viewed 37

I'm trying to get json data through json server. I create an angularjs application and generate a fake REST API with json server at http://localhost:3000/records which return json data successfully. But with $http service I cannot catch the data !

this is my service and controller code:

Service code: contact.service.js

   `(function () {
        var app = angular.module("contactApp");
    app.service("contactSvc", contactSvc);

    function contactSvc($http) {

        $http({
            method: "GET",
            url: "http://localhost:3000/records/"
        }).then(function mySuccess(response) {
            var msg = "succès !";
            this.res = response.data.records;
        });
    };})();`

code of the controller : contact.controller.js

 `(function (){ 
var app = angular.module("contactApp");
app.controller("contactCtrl", contactCtrl);

function contactCtrl(appName,contactSvc) {

    this.applicationName = appName;
    this.contacts = contactSvc.res;
    this.errmsg = contactSvc.msg;

    this.selectContact = function (index) {
        this.selectedContact = this.contacts[index];
    };
}})();`

and finaly code of index.html:

 `<div  ng-controller="contactCtrl as ctrl">
    <ul class="list-group">
      <li ng-repeat="contact in ctrl.contacts" ng-click="ctrl.selectContact($index)">
       {{contact.name.first +" "+contact.name.last}} </li>
     </ul>
    </div>`

Many thanks for your help

1 Answers

You should return promise from contactSvcfunction and when's resolved it should return response.data from that function.

var contactSvc= angular.module("contactApp").service("contactSvc", ['$http', function($http) {
    return {
        getcontacts: function() {    
            return $http.get('http://localhost:3000/records/')
            .then(function(response) {
                console.log("coming from servicejs", response.data);              
                return response.data;
            });
        }
    };
}]);

In your controller you should call the service function and use .then function to get call it when the getResponders service function resolves the $http.get call and assign the data to $scope.gotData

Code

 myService.getcontacts().then(function(data){
      this.contacts = data.records;
 });
Related