如何在AngularJS中使用axios库

Fer*_*nch 3 angularjs angular-promise axios

为什么axios回调更改显示在angularjs中而不使用$ apply

我试着爱可信图书馆angularjs,当我看到改变我很惊讶$scope被角检测到爱可信回调。我以为我必须打个电话$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)
Run Code Online (Sandbox Code Playgroud)

您知道为什么$apply在axios中不需要吗?

编辑:

georgeawg的评论帮助我看到了我$http在其他地方使用的信息,因此我猜测由触发的摘要循环$http也有助于axios回调被“消化”。

geo*_*awg 5

如何在AngularJS中使用axios库

使用$ 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;
  });
Run Code Online (Sandbox Code Playgroud)

只有在AngularJS执行上下文中应用的操作才能从AngularJS数据绑定,异常处理,属性监视等中受益。

另外,请使用$ timeout服务代替setTimeout

  $timeout(() => {
    $scope.timeoutResult = {message: "timeout!"});
  }, 2000)
Run Code Online (Sandbox Code Playgroud)

$超时服务集成了AngularJS框架及其摘要周期。

  • 您没有提供足够的信息来重现结果。我怀疑您的代码中还有其他您不知道的原因导致摘要循环和随后的数据绑定。 (2认同)