组件没有获取在已解决的 ES6 承诺调用中更改的变量的新状态

component not picking up new state of a variable changed inside a resolved ES6 promise call

这是我的第一个 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>

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

一种方法是将 ES6 promise 包装在 $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

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

有关详细信息,请参阅