angularjs - 组件未在已解析的 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>
解决方案
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 承诺中。当您处理可能是也可能不是承诺的对象,或者如果承诺来自无法信任的来源时,这很有用。
有关详细信息,请参阅
推荐阅读
- python - 如何使用正则表达式来帮助抓取 Web 数据?
- amazon-eks - standard_init_linux.go:219:exec 用户进程导致:exec 格式错误 ECR + Quarkus
- bash - 在多个子目录下执行多个同名的shell脚本
- javascript - TypeError:event.preventDefault 不是函数
- sql - 我可以在 access.form 而不是每个 form.event 中 c.connect 一次吗?
- css - 在两列行css中对齐div
- javascript - 在 Vercel 上托管时 NuxtJS 生产中的 URIError
- google-chrome - 如何设置 Chrome 插件清单,以便内容脚本仅在某些子域上运行?
- javascript - 在 Cypress 中,如何从定义的数组列表中单击特定值?
- python-3.x - 我正在尝试通过串行通信读取传感器数据,但是当我尝试读取它时,它只是在 python 中运行,但它没有显示任何值