javascript - 无法使用 $q 和 promise
问题描述
我想使用变量 StatusASof 在 inserthtml 函数中显示数据,如下所示。
App.controller("SS_Ctrl", function ($scope, $http, $location, $window, $sce, $q) {
var ShiftDetails = [];
function getMAStatusASof(Id) {
var defer = $q.defer();
$http({
method: 'GET',
url: 'http://xx/api/Sxxx/GetMAStatusASof',
params: { Id: Id }
}).then(function successCallback(response) {
StatusASof = response.data;
alert("getMAStatusASof : " + StatusASof); --> Got data from API here in this alert.
defer.resolve(response);
}, function errorCallback(response) {});
}
function insertHtml(dates, ShiftDetails, Id) {
// var promise = getMAStatusASof(Id); promise.then(
var defer = $q.defer();
getMAStatusASof(Id);
alert(StatusASof); --> alert says empty here
defer.resolve();
var Content;
Content = '<table class="clsTable"> <tr> <td rowspan="2">Cases ' + $scope.StatusASof + ' </td> <td rowspan="2">Total</td> ';
for (var i = 0; i <= 6; i++) {
if (i == daySeq - 1) {
Content = Content + '<td colspan="3" style="background-color:red"> {{dates[ ' + i + ']}} </td> ';
}
}
}
但是在显示结果时 $scope.StatusASof 是未定义的。看起来 $q.defer 不适合我。
仅从 getMAStatusASof(Id); 获取数据后如何继续执行代码?
有人可以在这里帮忙。
解决方案
更新
你需要return defer.promise;
function getMAStatusASof(Id) {
var defer = $q.defer();
$http({
method: 'GET',
url: 'http://xx/api/Sxxx/GetMAStatusASof',
params: { Id: Id }
}).then(function successCallback(response) {
StatusASof = response.data;
alert("getMAStatusASof : " + StatusASof); --> Got data from API here in this alert.
defer.resolve(StatusASof);
}, function errorCallback(response) {
deferred.reject(false);
});
return defer.promise;
}
你可以像这样使用这个功能:
getMAStatusASof(Id).then(function(res){
if(res){
$scope.StatusASof = res;
}
})
推荐阅读
- swift - 如何将变量的值作为参数传递给函数?
- javascript - 如何从迭代中停止javascript过滤器功能
- python - 创建包含两列数据框的 seaborn 直方图
- html - 我需要对齐文本,以便“当前”与其余导航链接位于同一行
- api - APiPlatform 将对象的返回对象而不是数组放在 oneToMany 关系上
- android - Android : 我如何知道来电的目的地?
- python - 试图以 XML 格式打开 URL 的语法错误
- c - 检查字符串是否包含没有库和正则表达式的小写和大写
- javascript - 如何隐藏存储在 JavaScript 中的 API 密钥?
- android - 在我所在位置周围 50 英里范围内查看谷歌地图