【问题标题】:angularjs: returning json data from service to controllerangularjs:将json数据从服务返回到控制器
【发布时间】:2013-09-13 07:41:02
【问题描述】:

我正在使用 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 方法。如果需要任何其他代码,请告诉我。

【问题讨论】:

  • 使this.getCustomers 返回一个承诺并使用.then 将其链接到init()。
  • @sza:我对 Angular js 很陌生...你能详细说明一下并将其发布在 ans 中,以便我标记它吗?

标签: angularjs xmlhttprequest


【解决方案1】:

当然。试试这个代码

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 非常感谢您对承诺的洞察力。
猜你喜欢
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多