AngularJS工厂服务没有向控制器返回动态数据

AngularJS Factory Service not returning dynamic data to controller

本文关键字:控制器 返回 动态 数据 工厂 服务 AngularJS      更新时间:2023-09-26

这是我的工厂服务,它正在从web服务获取数据

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

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

如果有一些静态/虚拟数据,它工作得很好。控制器正在获取数据并显示。

我哪里做错了?

感谢您的帮助。

谢谢

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