如何在 AngularJS 中使用 axios 库 [英] How to use the axios library with AngularJS

查看:32
本文介绍了如何在 AngularJS 中使用 axios 库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 axios 库" rel="nofollow noreferrer">angularjs 当我看到 axios 回调中 $scope 的变化被 angular 检测到时,我感到很惊讶.我想我必须像使用 setTimeout 一样调用 $apply.

I was trying axios library on angularjs and I was surprised when I saw that the changes to $scope in the axios callback were detected by angular. I thought I had to call $apply like, for example, when you use 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 吗?

Do you know why $apply is not needed in axios?

georgeawg 的评论帮助我看到我正在使用$http 在另一个地方,所以我猜 $http 触发的摘要循环正在帮助 axios 回调被消化";

A comment by georgeawg helped me see that I was using $http on another place, so I guess the digest cycle triggered by $http is helping axios callback to be "digested" too.

推荐答案

如何使用 axios 库 使用 AngularJS

使用 $q.when<将其 ES6 承诺带入 AngularJS 上下文/a>:

How to use the axios library with AngularJS

Bring its ES6 promises into the AngularJS context using $q.when:

  // 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 数据绑定、异常处理、属性监视等.

Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

还使用 $timeout 服务 而不是 setTimeout.

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

$timeout 服务与 AngularJS 框架及其消化循环.

The $timeout service is integrated with the AngularJS framework and its digest cycle.

这篇关于如何在 AngularJS 中使用 axios 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆