gpt4 book ai didi

angularjs - 如何在 AngularJS 中使用 axios 库

转载 作者:行者123 更新时间:2023-12-03 15:57:52 25 4
gpt4 key购买 nike

为什么 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中不需要吗?
编辑:
A comment by georgeawg帮助我看到我正在使用 $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)、异常处理、属性监视等。
也可以使用 $timeout service而不是 setTimeout .
  $timeout(() => {
$scope.timeoutResult = {message: "timeout!"});
}, 2000)
$timeout服务与 AngularJS 框架及其摘要循环集成。

关于angularjs - 如何在 AngularJS 中使用 axios 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46521516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com