$ http问题-在md-autocomplete Angular Material中解决承诺之前无法返回值 [英] $http issue - Values can't be returned before a promise is resolved in md-autocomplete Angular Material
问题描述
我在项目中使用Angular Material md-autocomplete
.通过这种方式,我可以使用$http
服务通过ajax调用从服务主机中获取建议列表.
I'm using Angular Material md-autocomplete
in my project. In that I'm getting the suggest listing from the Service Host via ajax call using $http
service.
问题:$ http问题-在兑现承诺之前无法返回值 在
md-autocomplete
角材料中解析
Issue: $http issue - Values can't be returned before a promise is resolved in
md-autocomplete
Angular Material
我的要求:我需要使用远程数据更新的建议列表
md-autocomplete
角材料-Ajax $http
服务中的源.
My Requirement: I need an updated Suggestion List using remote data
sources in md-autocomplete
Angular Material - Ajax $http
service.
我使用了Angular Material链接 https://material.angularjs.org/latest/demo/autocomplete
I used the approach as mentioned in Angular Material link https://material.angularjs.org/latest/demo/autocomplete
源代码:
场景1:
HTML源代码:
<md-autocomplete flex required
md-input-name="autocompleteField"
md-no-cache="true"
md-input-minlength="3"
md-input-maxlength="18"
md-selected-item="SelectedItem"
md-search-text="searchText"
md-items="item in querySearch(searchText)"
md-item-text="item.country" Placeholder="Enter ID" style="height:38px !important;">
<md-item-template>
<span class="item-title">
<span md-highlight-text="searchText" md-highlight-flags="^i"> {{item.country}} </span>
</md-item-template>
</md-autocomplete>
AngularJS脚本:
AngularJS Script:
//bind the autocomplete list when text change
function querySearch(query) {
var results = [];
$scope.searchText = $scope.searchText.trim();
if (query.length >=3) {
results = LoadAutocomplete(query);
}
return results;
}
//load the list from the service call
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;
}
方案2:
带有AngularJS源代码的HTML:
HTML with AngularJS Source Code:
<!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.0/angular-material.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Person to Select:</p>
<md-autocomplete
ng-disabled="isDisabled"
md-no-cache="noCache"
md-selected-item="selectedItem"
md-search-text-change="searchTextChange()"
md-search-text="searchText"
md-selected-item-change="selectedItemChange(item)"
md-items="item in Person"
md-item-text="item.Name"
md-min-length="0"
placeholder="Which is your favorite Person?">
<md-item-template>
<span md-highlight-text="ctrl.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>
<br/>
</div>
<script>
var app = angular.module('myApp', ['ngMaterial']);
app.controller('myCtrl', function ($scope, $http, $q) {
$scope.searchText = "";
$scope.Person = [];
$scope.selectedItem = [];
$scope.isDisabled = false;
$scope.noCache = false;
$scope.selectedItemChange = function (item) {
alert("Item Changed");
}
$scope.searchTextChange = function () {
$http({
method: "POST",
url: "https://www.bbminfo.com/sample.php",
params: {
token: $scope.searchText
}
})
.success(function (response) {
$scope.Person = response.records;
});
}
});
</script>
</body>
</html>
在场景1 中,我使用该函数来获取过滤后的列表md-items="item in querySearch(searchText)"
.但是在方案2 中,我使用了$scope
变量md-items="item in Person"
In Scenario 1, I used the function to fetch the filtered list md-items="item in querySearch(searchText)"
. But in Scenario 2, I used a $scope
variable md-items="item in Person"
请参阅快照
快照1:
我在这里搜索印度,但其中显示了印度的搜索结果.我在 Firefox浏览器Firebug 中调试了该问题,请参见上面显示的快照1 ,该请求是通过POST方法针对搜索字词 indian 发送的并且成功获得了一个匹配项作为JSON对象的响应,该响应显示在 SnapShot 1
Here I'm searching for indian but it shows the result for india. I debugged the issue in Firefox Browser Firebug, see the above Snapshot 1 it shows, the request was sent for the search term indian via POST Method and I got the response of one matching items as a JSON Object successfully, which is shown in the bottom of SnapShot 1
我在这种情况下发现的问题,在此之前无法返回值 诺言被兑现
The issue I find out in this case, the Values can't be returned before a promise is resolved
我尝试过的步骤:
案例1 :我在UI md-items="item in Person | filter: searchText"
中使用了AngularJS filter
,它提供了先前获取的远程数据的过滤列表,而不是当前获取的远程数据.在对文本框中的字符进行Backspacing时,它会显示不正确的建议列表.
Case 1: I used the AngularJS filter
in UI md-items="item in Person | filter: searchText"
, it gives the filtered list of previously fetched remote data not a currently fetched remote data. While on Backspacing the character in the textbox it shows the improper suggestion list.
情况2 :我试图通过在$http
服务中调用$scope.$apply()
来更新UI中的更改,但是失败.由于默认情况下$http
服务会调用$scope.$apply()
,因此显示该错误会向我抛出错误错误:[$ rootScope:inprog] ... .最终,我失败了.
Case 2: I tried to update the changes in UI by calling $scope.$apply()
within a $http
service, but it fails. Because $http
service calling the $scope.$apply()
by default, show it throws me an error Error: [$rootScope:inprog].... Finally in this attempt I failed.
案例3 :我在手动调用的函数内创建了一个函数,在$scope.$apply()
内手动推入了一个虚拟项,并将其弹出到$scope
变量中.绑定md-autocomplete
.但是我这次尝试失败了.因为在这里我也得到了与快照相同的输出.
Case 3: I created a function, within the function I'm manually called the $scope.$apply()
, within the function I manually pushed and poped one dummy item to the $scope
variable which is bind in the md-autocomplete
. But I failed in this attempt. Because here also I got a same output as same as in the snapshot.
function Ctrlm($scope) {
$scope.messageToUser = "You are done!";
setTimeout(function () {
$scope.$apply(function () {
$scope.dummyCntry = [
{
sno: 0,
country: ""
},
];
$scope.Person.push($scope.dummyCntry);
var index = $scope.Person.indexOf($scope.dummyCntry);
$scope.Person.splice(index, 1);
});
}, 10);
}
案例4 :我采用了与$ scope.$ watchCollection中的案例3"相同的方法.在这里我也遇到了挫折.
Case 4: I did the same approach as like "Case 3" within the $scope.$watchCollection. Here also I got a setback.
$scope.$watchCollection('Person', function (newData, oldDaata) {
$scope.dummyCntry = [
{
sno: 0,
country: ""
},
];
newData.push($scope.dummyCntry);
var index = newData.indexOf($scope.dummyCntry);
newData.splice(index, 1);
});
案例5 :我使用的是 jquery ajax调用,而不是$http
服务.在这种情况下,我使用$scope.apply()
手动更新了UI.我再次失败了,在这里我也得到了相同的输出.
Case 5: Instead of $http
service, I used the jquery ajax call. In that I used the $scope.apply()
to update the UI manually. I failed in this attempt once again, here also I got the same output.
$scope.searchTextChange = function () {
if (($scope.searchText != undefined) && ($scope.searchText != null)) {
$.ajax({
type: 'GET',
url: "https://www.bbminfo.com/sample.php?token=" + $scope.searchText,
success: function (response) {
$scope.$apply(function () {
$scope.Person = response.records;
});
},
error: function (data) {
$scope.$apply(function () {
$scope.Person = [];
});
},
async: true
});
} else {
$scope.Person = [];
}
}
在所有尝试中,我都无法解决该问题.
In all the attempts I can't able to fix the issue.
@georgeawg https://stackoverflow.com/users/5535245/georgeawg 建议我发布一个新问题,他说:"写一个新问题,描述您实际要完成的工作,包括所需的行为,迄今为止为解决问题所做的工作的摘要以及对您所遇到的困难的描述解决了这个问题."
@georgeawg https://stackoverflow.com/users/5535245/georgeawg suggested me to post a new question, he stated, "write a new question that describes what you are actually trying to accomplish, include the desired behavior, a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it."
我先前发布的参考问题
帖子1 : 帖子2 :
我的要求:我需要使用远程数据更新的建议列表
角材料 My Requirement: I need an updated Suggestion List using remote data
sources in Angular Material 在这方面请帮助我. 出于测试目的,请使用以下源代码 使用以下URL作为远程数据源: https://bbminfo.com/sample. php?token = ind Use the following URL for Remote Data Source: https://bbminfo.com/sample.php?token=ind 远程数据源URL包含国家/地区名称列表. The Remote Data Source URL contains the List of Countries Name. 通过点击下面的运行代码段按钮直接测试代码. Directly Test the Code by click the below Run Code Snippet button. 使用AngularJS源代码完成HTML: Complete HTML with AngularJS Source Code:
@KevinB https://stackoverflow.com/users/400654/kevin-b -给出了如何实施的想法.我真的非常感谢他...再次感谢凯文... @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. 源代码为
I Briefly explained about md-autocomplete in the following blog - http://www.increvcorp.com/usage-of-md-autocomplete-in-angular-material/ 这篇关于$ http问题-在md-autocomplete Angular Material中解决承诺之前无法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!md-autocomplete
-Ajax $http
服务中的源.
md-autocomplete
- Ajax $http
service.
<!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.0/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-change="searchTextChange()"
md-search-text="searchText"
md-selected-item-change="selectedItemChange(item)"
md-items="item in Person"
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) {
$scope.searchText = "";
$scope.Person = [];
$scope.selectedItem = [];
$scope.isDisabled = false;
$scope.noCache = false;
$scope.selectedItemChange = function (item) {
alert("Item Changed");
}
$scope.searchTextChange = function () {
$http({
method: "post",
url: "https://www.bbminfo.com/sample.php",
params: {
token: $scope.searchText
}
})
.success(function (response) {
$scope.Person = response.records;
});
}
});
</script>
</body>
</html>
推荐答案
<!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>