2017-02-08 3 views
-1

У меня есть md-автозаполнение, подключенное к списку, полученному от удаленного вызова данных. Я хочу заказать свои результаты в алфавитном порядке, но orderBy ожидает массив и не работает с обещанием.Угловой материал Autocomplete OrderBy Promise

СЦЕНАРИЙ 1

Это моя текущая реализация, которая работает с возвращенным обещание, но не поддерживает OrderBy.

HTML

<md-autocomplete 
    md-no-cache="true" 
    ng-model-options="{debounce: 250}" 
    md-selected-item="criteria.orderByClientUser" 
    md-search-text="searchText" 
    md-items="item in getClientUsers(searchText)" 
    md-item-text="item" 
    md-min-length="0" 
    placeholder="First Last"> 
    <md-item-template>{{item}}</md-item-template> 
    <md-not-found>No matches found.</md-not-found> 
</md-autocomplete> 

Контроллер

$scope.getClientUsers = function(text) { 
    if(!text) return []; 
    text = text.toLowerCase(); 
    return clientUserProfileService.findByName(text); 
} 

ClientUserProfileService

service.findByName = function(name) { 
    return $http.post(searchUrl, name, { withCredentials: true }).then(res => res.data); 
} 

СЦЕНАРИЙ 2

Эта реализация применяет данные к области действия, но функция выходит до того, как обещает решение, поэтому список автозаполнения не обновляется.

HTML

<md-autocomplete 
    md-no-cache="true" 
    ng-model-options="{debounce: 250}" 
    md-selected-item="criteria.orderByClientUser" 
    md-search-text-change="getClientUsers(searchText)" 
    md-items="item in userList | orderBy" 
    md-item-text="item" 
    md-min-length="0" 
    placeholder="First Last"> 
    <md-item-template>{{item}}</md-item-template> 
    <md-not-found>No matches found.</md-not-found> 
</md-autocomplete> 

Контроллер

$scope.userList = []; 

$scope.getClientUsers = function(text) { 
    if(!text) return []; 
    text = text.toLowerCase(); 
    clientUserProfileService.findByName(text) 
     .then(_.mountP($scope, "userList")); 
} 

ClientUserProfileService

service.findByName = function(name) { 
    return $http.post(searchUrl, name, { withCredentials: true }).then(res => res.data); 
} 

Есть ли способ настроить OrderBy работать с обещанием? Или есть способ отсрочить возврат getClientUsers до тех пор, пока обещание не будет разрешено? Этот запрос очень быстрый, поэтому я знаю, что могу просто отложить метод сервиса и обернуть его в малый тайм-аут, но это похоже на копту.

Цените свою помощь!

** ОБНОВЛЕНО КОД ** - По-прежнему приводит к обещанию возвращается из getClientUsers(), который не работает с OrderBy

Error: [orderBy:notarray] 

HTML

<md-autocomplete 
    md-no-cache="true" 
    ng-model-options="{debounce: 250}" 
    md-selected-item="criteria.orderByClientUser" 
    md-search-text="searchText" 
    md-items="item in getClientUsers(searchText) | orderBy" 
    md-item-text="item" 
    md-min-length="0" 
    placeholder="First Last"> 
    <md-item-template>{{item}}</md-item-template> 
    <md-not-found>No matches found.</md-not-found> 
</md-autocomplete> 

контроллер

$scope.getClientUsers = function(text) { 
    if(!text) return []; 
    text = text.toLowerCase(); 
    return clientUserProfileService.findByName(text) 
     .then(function (data) { 
      return data; 
     }); 
} 

ClientUserProfileService

service.findByName = function(name) { 
    return $http.post(searchUrl, name, { withCredentials: true }).then(res => res.data); 
} 

ответ

2

Сценарий № 2 должны возвращать обещание:

//Scenario #2 

$scope.userList = []; 

$scope.getClientUsers = function(text) { 
    if(!text) return []; 
    text = text.toLowerCase(); 
    //vvvv return derived promise 
    return clientUserProfileService.findByName(text) 
     .then(function (data) 
      //_.mountP($scope, "userList") 
      //do something to data 
      //vvvv return data to chain 
      return modifiedData; 
    ); 
} 

Поскольку вызов .then метода обещания возвращает новое производное обещание, то легко можно создать цепочку обещания.Можно создавать цепочки любой длины, и с обещание может быть разрешено с помощью другого обещания (которое отложит дальнейшее разрешение), можно приостановить/отложить разрешение обещаний в любой точке цепи. Это позволяет реализовать мощные API.

-- AngularJS $q Service API Reference - Chaining Promises


Чтобы упорядочить данные с помощью AngularJS orderBy фильтр:

$scope.getClientUsers = function(text) { 
    if(!text) return []; 
    text = text.toLowerCase(); 
    //vvvv return derived promise 
    return clientUserProfileService.findByName(text) 
     .then(function (data) 
      //_.mountP($scope, "userList") 
      //do something to data 
      var orderByData = $filter("orderBy")(data); 
      //vvvv return data to chain 
      return orderByData; 
    ); 
} 

Для получения дополнительной информации см AngularJS orderBy Filter API Reference.

+0

Возможно, я ошибаюсь, но когда я это осуществил, метод getClientUsers все еще возвращает обещание, а не данные, которые не поддерживаются orderBy. Это была та же ситуация, с которой я столкнулся со сценарием №1. Я неправильно истолковал ваш ответ? Я обновил вопрос с помощью моего текущего рабочего кода –

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