2016-08-12 72 views
0

这是我厂的服务,它是从Web服务AngularJS工厂服务不返回动态数据控制器

var customersFactory = function ($http) { 
    var customer = []; 
    var getCustomersURL = "http://localhost:50340/Services/CustomerService.asmx/GetCustomers"; 

    customer.XMLtoJSON = function (data) { 
     data = data.replace('<?xml version="1.0" encoding="utf-8"?>', ''); ; 
     data = data.replace('<string xmlns="http://tempuri.org/">', '').replace('</string>', ''); 
     return $.parseJSON(data); 
    }; 

    customer.GetCustomers = function() { 
     $http.post(getCustomersURL).success(function (data, status, headers, config) { 
      return customer.XMLtoJSON(data); 
     }).error(function (ata, status, headers, config) { }); 
    }; 

    return customer; 
}; 

app.factory('customersFactory', customersFactory); 

现在获取数据,这是被我的控制器使用

app.controller("CustomersController", function ($scope, customersFactory) { 
    var service = []; 
    service = customersFactory.GetCustomers(); 
    $scope.Customers = service; 

    if ((typeof (service) != 'undefined') && service.length > 0) { 
     service.then(function (result) { 
      $scope.Customers = result; 
     }); 
    } 
}); 

的服务的价值总是未定义或为空。数据没有从工厂传递到控制器。我调用一个简单的Web服务,没有花哨的API或WCF。

它有一些静态/虚拟数据,它的工作正常。控制器正在读取数据并正在显示。

我在哪里做错了?

任何帮助,非常感谢。

谢谢

回答

1

改变这一行var customer = [];这个var customer = {};

或者更好的是使之类......

改变这个返回承诺:

customer.GetCustomers = function() { 
     return $http.post(getCustomersURL).error(function (data, status, headers, config) { }); 
    }; 

和在控制器中的使用:

app.controller("CustomersController", function($scope, customersFactory) { 
    $scope.Customers = []; 

    customersFactory.getCustomers().success(function(data, status, headers, config) { 
    $scope.Customers = customersFactory.XMLtoJSON(data); 
    }); 
}); 
+0

非常感谢WalksAway。收到。我明白我出错的地方。非常感谢。 – Vamsi