невозможно использовать $ q и обещать - PullRequest
0 голосов
/ 03 апреля 2019

Я хочу использовать переменную StatusASof для отображения данных в функции insertthtml, как показано ниже.

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);

Может ли кто-нибудь помочь здесь.

Ответы [ 3 ]

1 голос
/ 03 апреля 2019

Обновление

нужно 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;
  }
})
0 голосов
/ 03 апреля 2019

Невозможно обновить сообщение @ Daniël Teunkens, используя следующий код (от "}" до ")"). Поэтому добавляем как новый ответ.

getMAStatusASof(Id).then(function(result) {
   // your code here. your HTML content.
     ....
  console.log(result);
})

Надеюсь, будет работать.

0 голосов
/ 03 апреля 2019

Нет необходимости использовать $ 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, как упоминал Джазиб.

Но, как я уже сказал, поскольку $ http уже возвращает обещание, выполнение всего $ 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...