作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么 axios 回调更改显示在 angularjs 中,而不使用 $apply
我在尝试 axios图书馆 angularjs当我看到对 $scope
的更改时,我感到很惊讶在 axios 回调中被 angular 检测到。我以为我必须调用 $apply
例如,当您使用 setTimeout
时.
// axios example
axios.get(url).then((response) => {
// Here I don't need $apply, why??
$scope.axiosResult = response.data;
});
// setTimeout example
setTimeout(() => {
// Here I need $apply for the timeoutResult to appear on the HTML
$scope.$apply(() => $scope.timeoutResult = {message: "timeout!"});
}, 2000)
你知道为什么
$apply
axios中不需要吗?
$http
在另一个地方,所以我猜是
$http
触发的摘要循环也在帮助 axios 回调被“消化”。
最佳答案
如何使用axios library使用 AngularJS
使用 $q.when 将其 ES6 promise 带入 AngularJS 上下文:
// axios example
̶a̶x̶i̶o̶s̶.̶g̶e̶t̶(̶u̶r̶l̶)̶.̶t̶h̶e̶n̶(̶(̶r̶e̶s̶p̶o̶n̶s̶e̶)̶ ̶=̶>̶ ̶{̶
$q.when(axios.get(url)).then((response) => {
$scope.axiosResult = response.data;
});
只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定(bind)、异常处理、属性监视等。
setTimeout
.
$timeout(() => {
$scope.timeoutResult = {message: "timeout!"});
}, 2000)
$timeout服务与 AngularJS 框架及其摘要循环集成。
关于angularjs - 如何在 AngularJS 中使用 axios 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46521516/
我是一名优秀的程序员,十分优秀!