【问题标题】:Asynchronous request on bootstrap AngularJS uib-typeahead引导AngularJS uib-typeahead上的异步请求
【发布时间】:2017-09-29 22:27:14
【问题描述】:

我正在尝试在服务器端搜索用户输入的名称,并使用引导程序 3 uib-typeahead 提供建议,但是(尽管我硬编码了要返回的值 - 出于测试目的),没有返回值预输入下拉菜单。我的猜测是,由于这是一个异步请求,因此在检索请求数据时已经返回了任何数据。

有什么方法可以从服务器端检索数据,同时预输入正在侦听?

$scope.test_search = function(test_name){
    var curr_url = '/plan/ajax/test/';

    var search_response =  $http.get(curr_url,{
        cache: true,
        params:{'name': test_name, 'csrfmiddlewaretoken': $cookies.csrftoken}
    }).then(function successCallback(response) {
        console.log(response.data);
        //return response.data;
        var test = [
            {country: "US", name : 'Alabama'}
        ];
        return test;

    }, function errorCallback(response) {
        alert('Error');
    });

},
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="col-lg-6">
    <pre>Model: {{new_ingredient_selected | json}}</pre>
    <input type="text"
           ng-model = "new_ingredient_selected"
           placeholder="test test"
           uib-typeahead="ingredient.name for ingredient in test_search($viewValue) |  filter:{name:$viewValue}"
           typeahead-loading="loadingLocations"
           typeahead-no-results="noResults"
           typeahead-on-select="onTypeaheadIngredientSelect($item, $label, $index)"
           typeahead-wait-ms ="400"
           class="form-control">

    <i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
    <div ng-show="noResults">
      <i class="glyphicon glyphicon-remove"></i> No Results Found
    </div>
</div>

【问题讨论】:

    标签: angularjs twitter-bootstrap-3 angular-ui-bootstrap bootstrap-typeahead


    【解决方案1】:

    test_search 函数需要 return 语句:

    $scope.test_search = function(test_name){
        var curr_url = '/plan/ajax/test/';
    
        var search_response =  $http.get(curr_url,{
            cache: true,
            params:{'name': test_name, 'csrfmiddlewaretoken': $cookies.csrftoken}
        }).then(function successCallback(response) {
            console.log(response.data);
            //return response.data;
            var test = [
                {country: "US", name : 'Alabama'}
            ];
            return test;
    
        }, function errorCallback(response) {
            alert('Error');
            //IMPORTANT
            //RE-THROW the error
            ͟t͟h͟r͟o͟w͟ ͟r͟e͟s͟p͟o͟n͟s͟e͟;͟
        });
    
        //IMPORTANT
        //RETURN the promise
        ͟ ͟r͟e͟t͟u͟r͟n͟ ͟s͟e͟a͟r͟c͟h͟_͟r͟e͟s͟p͟o͟n͟s͟e͟;͟
    
    };
    

    当函数缺少return 语句时,它返回值undefined

    在拒绝处理程序中re-throw 的错误响应也很重要。否则,被拒绝的 Promise 将转换为一个已履行的 Promise,其解析值为 undefined

    【讨论】:

    • 通过等待异步请求的回调然后返回检索到的数据解决了问题。
    猜你喜欢
    • 2019-09-22
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多