$http issue - Values can't be returned before a promise is resolved in md-autocomplete Angular Material

心不动则不痛 提交于 2019-11-30 15:58:38
B.Balamanigandan

@KevinB https://stackoverflow.com/users/400654/kevin-b - Gives the Idea how to implement. I really thank him... Once again thanks alot Kevin...

I got the Exact solution, what I need.

The Source Code is

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>

<!-- Angular Material Library -->
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.0.4/angular-material.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl"> 

<p>Country to Select:</p>
<md-content>
<md-autocomplete
          ng-disabled="isDisabled"
          md-no-cache="noCache"
          md-selected-item="selectedItem"
          md-search-text="searchText"
          md-items="item in searchTextChange(searchText)"
          md-item-text="item.country"
          md-min-length="0"
          placeholder="Which is your favorite Country?">
        <md-item-template>
          <span md-highlight-text="searchText" md-highlight-flags="^i">{{item.country}}</span>
        </md-item-template>
        <md-not-found>
          No Person matching "{{searchText}}" were found.
        </md-not-found>
      </md-autocomplete>
      </md-content>
      <br/>
</div>

<script>
    var app = angular.module('myApp', ['ngMaterial']);

    app.controller('myCtrl', function ($scope, $http, $q, GetCountryService) {

        $scope.searchText = "";
        $scope.Person = [];
        $scope.selectedItem = [];
        $scope.isDisabled = false;
        $scope.noCache = false;

        $scope.selectedItemChange = function (item) {
            //alert("Item Changed");
        }
        $scope.searchTextChange = function (str) {
			return GetCountryService.getCountry(str);
        }

    });
	
	app.factory('GetCountryService', function ($http, $q) {
        return {
            getCountry: function(str) {
                // the $http API is based on the deferred/promise APIs exposed by the $q service
                // so it returns a promise for us by default
				var url = "https://www.bbminfo.com/sample.php?token="+str;
                return $http.get(url)
                    .then(function(response) {
                        if (typeof response.data.records === 'object') {
                            return response.data.records;
                        } else {
                            // invalid response
                            return $q.reject(response.data.records);
                        }

                    }, function(response) {
                        // something went wrong
                        return $q.reject(response.data.records);
                    });
            }
        };
    });
</script>
</body>
</html>

I Briefly explained about md-autocomplete in the following blog - http://www.increvcorp.com/usage-of-md-autocomplete-in-angular-material/

I struggled with this as well for a bit. Basically you should actually be returning a promise that returns the content.

This is my "search" function

$scope.searchData = function (searchTxt) {
        return $http.get('/TestSearch', { params: { searchStr: searchTxt } })
            .then(function(response) {

                return response.data;
            });
    };

Also I'm not sure what version of angular you're running but I think .success was deprecated.

And here is my md-autocomplete as well

<md-autocomplete placeholder="Text goes here"
                 md-selected-item="vm.autocomp"
                 md-search-text="searchText"
                 md-items="item in searchData(searchText)"
                 md-item-text="item">
    <span md-highlight-text="searchText">{{item}}</span>
</md-autocomplete>

EDIT1: Sorry original JS was in TypeScript. Fixing that now

The Answer Marked is Correct.

  • .then() - full power of the promise API but slightly more verbose
  • .success() - doesn't return a promise but offers slightly more convenient syntax

Why not just put return countryList inside the success function.

function LoadAutocomplete(id) {
    var countryList = [];
    $http({
            method: "post",
            url: "https://www.bbminfo.com/sample.php",
            params: {
                token: id
            }
        })
        .success(function (response) {
            countryList = response.records;
            return countryList;
        })
        .error(function (response) {
            countryList = [];
            return countryList;
        });
}

edit due to deprecation of .success and .error methods:

function LoadAutocomplete(id) {
    var countryList = [];
    $http({
            method: "post",
            url: "https://www.bbminfo.com/sample.php",
            params: {
                token: id
            }
        })
        .then(function (response) {
            countryList = response.data.records;
            return countryList;
        },function () {
            countryList = [];
            return countryList;
        });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!