首页 > 解决方案 > 组件未在已解析的 ES6 承诺调用中获取已更改变量的新状态

问题描述

这是我正在更新但运行不佳的第一个 angularjs 应用程序。基本上我有一个微调器,我需要在计算时显示然后将其关闭。我的承诺得到了很好的解决,但该组件没有获得新的价值。如果我单击一个实际更改加载变量的按钮,它确实会起作用,因为组件会获取该false值。

但我希望在承诺完成后将其关闭。它确实解决了,我确实vm.loading = false很好地达到了这个值,但组件没有得到那个新值。

(function () {

    var app = angular.module('APP').controller('APPController',
    ['$q', '$scope', '$http', '$timeout', '$location', '$filter', 'dataservice', '$routeParams', controller]);

    function controller($q, $scope, $http, $timeout, $location, $filter, dataservice, $routeParams) {

        // The controller's API to which the view binds
        var vm = this;
        vm.loading = false;
        vm.data = null; // GET THIS FROM API
        getSettings();

        function getSettings() {

            vm.loading = true;

            var pArray = []; // promises Array
            var p1 = vm.ds.fetchExstingSettings(10);
            pArray.push(p1);

            $q.all(pArray)
                .then(function (data) {
                    // get api data now    
                    fetchData().then(done => {
                        vm.loading = false; // reaching here well
                    })    
                })
                .catch(
                function (err) {
                    alert(err);
                    return null;
                })
                .finally(function () {    
                    $timeout(function () {
                        vm.searchLoading = 0;
                        $scope.$apply();
                    });
                });
        }


      async function fetchData() {    
          var result = await $http.get('http://localhost:4228/Api/data');
          vm.data = result;             
      }    
      function saveChanges() {
          vm.loading = false; // this works     
      }    
    }
})();// JavaScript source code

html:

<div class="text-center" ng-if="vm.loading == true">
    <i class="fa fa-spin fa-spinner fa-5x"></i>
</div>

标签: angularjsangular-promise

解决方案


async/使用的 ES6 Promiseawait没有与 AngularJS 框架及其执行上下文集成。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等。

一种方法是将 ES6 承诺包装在$q.when

  $q.all(pArray)
    .then(function (data) {
        // get api data now    
        $q.when(fetchData()).then(done => {
            vm.loading = false; // reaching here well
        })    
  })

从文档:

$q.when

将一个可能是值或(第 3 方)then-able 承诺的对象包装到 $q 承诺中。当您处理可能是也可能不是承诺的对象,或者如果承诺来自无法信任的来源时,这很有用。

有关详细信息,请参阅


推荐阅读