【发布时间】:2017-05-09 23:40:23
【问题描述】:
使用 AngularJS 1.6.1 (ES6/Babel)...控制器调用一个使用 $http.post() 的服务方法,所以我认为它会自动运行摘要。必须添加 $timeout 来强制它(最好避免使用 $scope.$apply,因为这是一个 Angular 组件,很快就会升级到 AngularJS 2)。
有没有比我做的更好的方法? then() 是否应该从最初的 $http.post 中运行摘要循环?如果我不包含 $timeout,则视图中不会更新任何内容。
Place Order 按钮提交一个表单,其 ngClick 为 $ctrl.placeOrder(checkout):
placeOrder(form) {
if(form.$valid) {
return this.Cart.placeOrder()
.then(saleResponse => {
// Page has {{ $ctrl.pageName }} but won't update without digest cycle
this.pageName = 'Order Confirmation'; // displays confirmation
form.$setPristine(); // treat the fields as untouched
form.$submitted = false; // reset submitted state
// Force a digest to run. Why is this needed?
this.$timeout(() => this.pageName);
})
.catch(saleResponse => {
form.$submitted = false;
this.errorMessage = saleResponse.message;
if(this.errorMessage.includes('card')) this.focusOnCardNumber();
});
}
}
这里是 Cart.placeOrder():
placeOrder() {
// braintreeHostedFieldsTokenize() is a wrapper to return new Promise for their callback-based API
return this.braintreeHostedFieldsTokenize(this.hostedFieldsInstance)
.then(this.postOrderInformation.bind(this));
}
和 Cart.postOrderInformation()
postOrderInformation(payload) {
const orderInformation = {
nonceFromClient: payload.nonce,
purchaser: this.purchaser,
recipient: this.recipient,
cartItems: this.cartItems
};
return this.$http
.post('/api/order', orderInformation)
.then(orderResponse => {
this.confirmation = orderResponse.data;
if(!orderResponse.data.success) throw orderResponse.data;
return this.confirmation;
});
}
关于我可能在哪里出错需要使用 $timeout 有什么想法吗?我的假设是 $http.post 的 then() 会自行运行摘要循环,因为它是 AngularJS。提前致谢。
【问题讨论】:
标签: angularjs angular-promise es6-promise angularjs-digest