Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the axios library with AngularJS

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.

like image 780
Ferran Maylinch Avatar asked Oct 02 '17 07:10

Ferran Maylinch


People also ask

Can I use Axios with Angular?

Axios is also a promise-based HTTP client that can be used in plain JavaScript as well as in advanced JavaScript frameworks like React, Vue. js, and Angular.

How do we pass data and get data using HTTP in Angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

What is $HTTP in AngularJS?

The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP. For unit testing applications that use $http service, see $httpBackend mock.

What is typescript Axios?

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase).


1 Answers

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.

like image 168
georgeawg Avatar answered Oct 04 '22 17:10

georgeawg