2015-01-16 2 views
1

Я использую угловой, и данные возвращаются из моего вызова api. Проблема в том, что мой список не заполняется.Почему этот список не заполняется данными?

первый частичный:

<div ng-controller="CustomerController" data-ng-init="init()" class="col-md-2"> 
    <select ng-model="customerKey" ng-options="customer.Key as customer.Value for customer in customers"></select> 
</div> 

второй частичный:

<div ng-controller="CustomerController"> 
    <div class="col-md-2 col-md-offset-5" style="outline: 1px solid black; margin-top: 1%"> 
     <div class="text-center"> 
      <div class="radio-inline" ng-repeat="customerOption in customerOptions"> 
       <input type="radio" id="{{customerOption.Value}}" name="customer" ng-change="getCustomers(customerType)" ng-model="customerType" ng-value="customerOption.Key" ng-checked="customerOption.Checked" />{{customerOption.Value}} 
      </div> 
     </div> 
    </div> 
</div> 

Контроллер:

var customer = angular.module('customer', []); 

customer.controller('CustomerController', [ 
    "$scope", "customerService", 
    function($scope, customerService) { 
     $scope.customerOptions = CustomerOptions; 

     $scope.getCustomers = function(customerType) { 
      $scope.showContent = false; 
      customerService.get(customerType).then(function (data) { 
       $scope.customers = data; 
      }); 
     }; 

     $scope.init = function() { 
      $scope.getCustomers("1"); 
     } 
    } 
]); 

обслуживание:

app.service('customerService', [ 
"$http", function ($http) { 
    this.get = function(customerType) { 
     var customers; 
     if (customerType == "1") { 
      getProduction().then(function(result) { customers = result.data; }); 
     } else if (customerType == "2") { 
      getTest().then(function(result) { customers = result.data; }); 
     } else { 
      getAll().then(function(result) { customers = result.data; }); 
     } 
     return customers; 
    }; 

    var getTest = function() { 
     return $http({ 
      method: "GET", 
      url: "api/Customer/GetTest", 
     }) 
     .success(function (data) { 
      return data; 
     }); 
    }; 

    var getProduction = function() { 
     return $http({ 
      method: "GET", 
      url: "api/Customer/GetProduction", 
     }) 
     .success(function (data) { 
      return data; 
     }); 
    }; 

    var getAll = function() { 
     return $http({ 
      method: "GET", 
      url: "api/Customer/GetAll", 
     }) 
     .success(function (data) { 
      return data; 
     }); 
    }; 
    } 
]); 

Если вы нажмете на любой из переключателей, они вернут соответствующий список в сервисную функцию; однако я не могу получить список выбора для заполнения этими данными

+0

Что произойдет, если вы вызываете '$ scope.getCustomers (" 1 ");' непосредственно в конце вашего файла контроллера вместо перехода через ng-init? – sergiocruz

+1

Не могли бы вы создать скрипку или plunkr с этим? – aa333

ответ

3

Проблема в том, что служба возвращает объект клиентов вместо обещаний, которые ищет метод контроллера.

Он должен работать, если вы вернете обещание от службы и оставьте управление успехом/ошибкой контроллеру.

app.service('customerService', [ 
    "$http", function ($http) { 
    this.get = function(customerType) { 
    var customers; 
    if (customerType == "1") { 
     return getProduction(); 
    } else if (customerType == "2") { 
     return getTest(); 
    } else { 
     return getAll(); 
    } 
}; 

Контроллер:

$scope.getCustomers = function(customerType) { 
     $scope.showContent = false; 
     customerService.get(customerType).then(function (results) { 
      $scope.customers = results.data; 
     }); 
    }; 
2

В then обработчики в вашем методе CustomerService get() присваиваем результаты вызова HTTP к локальной customers переменной, но это не решает ничего. К тому времени, когда это произойдет, customers уже был возвращен вызывающему абоненту как undefined, и вы, скорее всего, получите сообщение об ошибке, когда вы вызываете then() по этому значению.

Вы должны вернуть обещание get() и then() обработчиков внутри get() необходимости иметь return заявление в них:

this.get = function(customerType) { 
    if (customerType == "1") { 
     return getProduction().then(function(result) { return result.data; }); 
    } else if (customerType == "2") { 
     return getTest().then(function(result) { return result.data; }); 
    } else { 
     return getAll().then(function(result) { return result.data; }); 
    } 
}; 

Существует довольно много дублирования здесь, и это может быть уложено:

Смежные вопросы