首页 > 解决方案 > 无法使用 $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); 获取数据后如何继续执行代码?

有人可以在这里帮忙。

标签: javascriptangularjsangularjs-scopeangular-promiseangularjs-q

解决方案


更新

你需要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;
  }
})

推荐阅读