如何在AngularJS中使用axios库

编程入门 行业动态 更新时间:2024-10-09 15:16:11
本文介绍了如何在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 :

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库

本文发布于:2023-11-28 04:44:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   AngularJS   axios

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!