AngularJS:从服务返回JSON数据给控制器

5

我正在使用angular js和spring mvc开发一个Web应用程序。

它正在调用spring mvc rest服务并将数据传递给angular js服务,但我无法在服务中看到相同的数据。

controllers.js

app.controller('CustomersController', function($scope, customersService){

init();
function init(){
    var data =customersService.getCustomers();
    $scope.customers = data;
}

$scope.insertCustomer = function(){
    var firstName = $scope.newCustomer.firstName;
    var lastName = $scope.newCustomer.lastName;
    var city = $scope.newCustomer.city;
    customersService.insertCustomer(firstName, lastName, city);
    $scope.newCustomer.firstName = '';
    $scope.newCustomer.lastName = '';
    $scope.newCustomer.city = '';
};

$scope.deleteCustomer = function(id){
    customersService.deleteCustomer(id);
};
});

app.controller('NavbarController', function ($scope, $location) {
    $scope.getClass = function (path) {
        if ($location.path().substr(0, path.length) == path) {
            return true;
        } else {
            return false;
        }
    };
});

customersService.js

app.service('customersService', function($http, $log) {

this.getCustomers = function() {
    $http({
        method : 'POST',
        url : '/CustomerManagementApp/customers/all'
    }).success(function(data, status, headers, config) {
        $log.log('Done');
        angular.forEach(data, function(c) {
            $log.log(c.firstName);
        });
        customers = data;
        return customers;
    });     
};

this.insertCustomer = function(firstName, lastName, city) {
    var topID = customers.length + 1;
    customers.push({
        id : topID,
        firstName : firstName,
        lastName : lastName,
        city : city
    });
};

this.getCustomer = function(id) {

};

this.deleteCustomer = function(id) {

};

var customers = {};
});

我能够在服务中使用forEach循环打印所有数据。但是在控制器中,它显示为空对象数组Object { }。

Firebug控制台没有错误。我正在使用POST方法。如果需要其他代码,请告诉我。


1
this.getCustomers 改为返回一个 Promise,并在 init() 中使用 .then 进行链式调用。 - zs2020
@sza:我非常新手AngularJS……你能否稍微详细解释一下,并在答案中发布,这样我就可以标记它了吗? - Priyank Thakkar
1个回答

16

好的,请尝试这段代码

function init(){
    customersService.getCustomers().then(function(response){
        $scope.customers = response.data;
    });
}

this.getCustomers = function() {
    var promise = $http({
        method : 'POST',
        url : '/CustomerManagementApp/customers/all'
    }).success(function(data, status, headers, config) {
        $log.log('Done');
        angular.forEach(data, function(c) {
            $log.log(c.firstName);
        });
        customers = data;
        return customers;
    });    

    return promise; 
};

Promise是一个用于与异步执行的操作结果进行交互的对象接口,表示该操作的结果可能在任何时间点上都未完成。


它起作用了。我只需要做data.data,非常感谢你对Promise的洞察力。 - Priyank Thakkar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接