如何在AngularJS中正确使用自定义服务

时间:2014-10-27 11:54:20

标签: javascript angularjs

我正在尝试将控制器逻辑移动到服务中。我添加了DataService并注入了$ http。然后loadData()方法返回JSON。我已将此服务注入TestController并调用提到的函数,但它不起作用。相同的简单逻辑可以从控制器正常工作。我应该改进什么? :)

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;
    };
}

我的观点看起来很简单:

<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="angular.js@1.2.25" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
    <script src="script.js"></script>
</body>

1 个答案:

答案 0 :(得分:1)

代码store.loadData中的

在响应来自后端之前返回undefined。所以使用这段代码:

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')

    };
}