0

I'm trying to move my controller logic to a service. I've added DataService and injected $http. Then loadData() method returns JSON. I've injected this service into a TestController and called mentioned function, but it doesn't work. The same simple logic worked correctly from a controller. What should I improve? :)

var app = angular.module('TestApp', []);
app.controller('TestController', TestController);
app.service('DataService', DataService);

function TestController(DataService) {
    var vm = this;
    vm.personalInfo = DataService.loadData();
}

function DataService($http) {
    var store = this;
    store.personInfo = [];

    store.loadData = function(){
        $http.get('data.json')
        .success(function(data){
        store.personInfo = data;
    })
    .error(function(){
        store.personInfo = "Error occured";
    });

    return store.personInfo;
    };
}

My view looks as easy as that:

<body ng-app="TestApp" ng-controller="TestController as test">
    <h1>Hello Plunker!</h1>

    <p ng-repeat="item in test.personalInfo" ng-bind="item.firstname"></p>

    <script data-require="[email protected]" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
    <script src="script.js"></script>
</body>
2
  • the first step is to define what you mean by the term "does not work" : ) Commented Oct 27, 2014 at 11:56
  • and, if you expect the loadData to return anything but [], then it won't because the call to $http is asynchronous. You need to set your vm.personalInfo when the success/error callback is called. Commented Oct 27, 2014 at 11:58

1 Answer 1

1

in your code store.loadData returning undefined before response come from backend. so use this code:

var app = angular.module('TestApp', []);
app.controller('TestController', TestController);
app.service('DataService', DataService);

function TestController(DataService) {
    var vm = this;
    DataService.loadData().then(function(data) {
            vm.personalInfo = data.data
        })
        .catch(function(err) {
            console.log(err)
        })
}

function DataService($http) {
    var store = this;
    store.personInfo = [];

    store.loadData = function() {
        return $http.get('data.json')

    };
}
Sign up to request clarification or add additional context in comments.

2 Comments

It looks reasonable, but still doesn't work. See here plnkr.co/edit/wgcAFS4y1t0z1v7fFgvl?p=preview
use data.data in controller see plunker plnkr.co/edit/2mR6PtFbS927iRApveL7?p=preview

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.