AngularJS Factory Service不将动态数据返回给控制器

时间:2016-08-12 10:12:46

标签: javascript 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 个答案:

答案 0 :(得分:1)

将此行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);
  });
});

和控制器中的用法:

<div class="wrap">
  <div class="aside">
  I want this block to be scrolled vertically if height is greater than Main Block's height.<br>
  The height of "wrap" block should be the same like Main Block's height.
  <Br><br>
    long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text
  </div><div class="main"> Main Block </div>
</div>
相关问题