5

Why axios callback changes are displayed in angularjs, without using $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)

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

EDIT:

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.

Community
  • 1
  • 1
Ferran Maylinch
  • 10,919
  • 16
  • 85
  • 100
  • I never use $apply, and I use a bunch of 3rd party AngularJS modules. Did you try $timeout (AngularJS) instead of setTimeout? – Christian Bonato Oct 02 '17 at 08:00
  • My question was specifically why axios callback is participating in data-binding although I'm not using `$q` or `$apply`. I think I'm missing something about how angularjs works... – Ferran Maylinch Oct 02 '17 at 10:58

1 Answers1

8

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;
  });

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

Also use the $timeout service instead of setTimeout.

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

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

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • Thank you! Although my question was specifically why axios callback is participating in data-binding although I'm not using `$q` or `$apply`. – Ferran Maylinch Oct 02 '17 at 10:57
  • 2
    You have not provided enough information to reproduce your results. I suspect something else in your code of which you are not aware is causing a digest cycle and the subsequent data binding. – georgeawg Oct 02 '17 at 12:09
  • 1
    Oh, I see! It's because I'm using `$http` on another place, and I guess the digest cycle triggered by `$http` is helping axios callback to be "digested" too. Thanks! – Ferran Maylinch Oct 02 '17 at 14:26