我想使用变量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)获取数据后,如何继续执行代码?

有人可以帮忙吗?

最佳答案

无需在这里使用$ q.defer()...

做就是了



function getMAStatusASof(Id) {
  return $http({
    method: 'GET',
    url: 'http://xx/api/Sxxx/GetMAStatusASof',
    params: { Id: Id }
  })
  .then(function successCallback(response) {
    return response.data;
  })
  .catch(function errorCallback(response) {
    return null;  //Effectively swallow the error an return null instead.
  });
}





然后,使用



getMAStatusASof(Id).then(function(result) {
  console.log(result);
});
//No .catch, as we've caught all possible errors in the getMAStatusASof function





如果您真的想使用$ q.defer(),则该函数将需要返回defer.promise,如Jazib所述。

但是就像我说的那样,由于$ http已经返回了一个promise,所以整个$ q.defer()+ return defer.promise事情是多余的。

相反,仅在您需要包装的东西本身不返回承诺时才使用该构造。例如,当您打开启动模式时,希望在用户单击关闭按钮时得到通知



function notifyMeOfClosing() {
  var deferred = $q.defer();
  bootbox.confirm("This is the default confirm!", function(result){
    if(result) {
      deferred.resolve();
    }
    else {
      deferred.reject();
    }
  });
  return deferred.promise;
}

10-05 20:29
查看更多