【问题标题】:How to use the axios library with AngularJS如何在 AngularJS 中使用 axios 库
【发布时间】:2018-11-24 14:11:01
【问题描述】:

为什么axios回调变化在angularjs中显示,不使用$apply

我在angularjs 上尝试axios 库,当我看到axios 回调中$scope 的更改被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)

你知道为什么axios不需要$apply吗?

编辑:

A comment by georgeawg 帮助我看到我在另一个地方使用了$http,所以我猜$http 触发的摘要循环也在帮助 axios 回调被“消化”。

【问题讨论】:

  • 我从不使用 $apply,我使​​用了一堆 3rd 方 AngularJS 模块。您是否尝试过 $timeout (AngularJS) 而不是 setTimeout?
  • 我的问题具体是为什么 axios 回调参与数据绑定,尽管我没有使用 $q$apply。我想我错过了一些关于 angularjs 是如何工作的......

标签: angularjs angular-promise axios


【解决方案1】:

如何在 AngularJS 中使用axios library

使用 $q.when 将其 ES6 承诺带入 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 数据绑定、异常处理、属性监视等。

同时使用$timeout service 代替setTimeout

  $timeout(() => {
    $scope.timeoutResult = {message: "timeout!"});
  }, 2000)

$timeout 服务与 AngularJS 框架及其摘要循环集成。

【讨论】:

  • 谢谢!虽然我的问题具体是为什么 axios 回调参与数据绑定,尽管我没有使用 $q$apply
  • 您没有提供足够的信息来重现您的结果。我怀疑您的代码中您不知道的其他内容正在导致摘要循环和随后的数据绑定。
  • 哦,我明白了!这是因为我在另一个地方使用了$http,我猜$http触发的摘要循环也在帮助axios回调被“消化”。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-06-29
  • 2021-03-04
  • 2019-05-19
  • 2019-02-02
  • 2019-04-08
  • 2018-07-23
相关资源
最近更新 更多