Angular vs. React vs. Vue (Part III: AJAX)

Requesting data from a server via AJAX/XMLHttpRequest is ubiquitous when implementing a single page application. In this article, I’m comparing the use of AJAX in Angular (version 6.0.3), React (version 16.4.1), and Vue (version 2.5.16).  I implemented the AJAX operations in a “To Do” app I created in part II.

I’ve set up a remote server which provides APIs to add a new to-do item, to remove a to-do item, and to list to-do items.

Angular provides a module HttpClient to allow your app to execute typical AJAX requests (POST, GET, etc). React’s documentation suggests that you can use any AJAX library with React. The documentation lists some common AJAX library such as axios, jQuery AJAX, and the browser’s built-in window.fetch. Vue hardly provides any hint regarding incorporating AJAX operations. Tucked in their website is the Cookbook section which has the article “Using Axios to Consument APIs.” I created a wrapper for axios and used it for both React and Vue

Sample Code

Angular

React

Vue


Angular’s HttpClient instance is available to be injected to any class once you import the HttpClient module from @angular/common/http library. The module provides the methods get(), post(), and other methods to do typical AJAX requests.

axios, an HTTP client library I used for React and Vue, is heavily inspired by Angular’s HttpClient, so the methods provided by axios will look familiar if you’ve used HttpClient. You can install axios using NPM.

When executing an AJAX request, typically you want to do it as early as possible but not to early as the component is loaded. A component in these three frameworks has a lifecycle and hooks are available so that an operation can be executed within the lifecycle. For an Angular, React, and Vue component, the recommendation is to execute any AJAX request the earliest inside the ngOnInit, componentDidMount, and mounted lifecycle hook, respectively.

A major difference between Angular’s HttpClient and axio‘s HTTP client is that HttpClient is based on Observable while axios library is based on Promise. For simple operations as used by this “To Do” app, there’s hardly any difference in the implementation between using an Observable or Promise-based HTTP client.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.