Blog postWhat is Angular observable?

What is Angular Observable

Published August 03, 2018

If you want to use Angular but feel a little intimidated by the terminology or heard about Observables and would like to know what it means or even if you are an Angular developer but still not sure that you understand the subject. Look no further because this tutorial is meant to assist you in understanding this core concept of Angular.

In this tutorial we'll learn:

  1. Why use Observable?
  2. How Observable works in Angular?
  3. Conclusion

# Why use Observable?

In the following tutorials, we will explain the use of Ajax and develop an application based on PHP and Angular. The all thing is based on an asynchronous code, so it is very important to understand the special way in which Angular handles such code.

Angular uses Observable to treat asynchronous code. The same way that we use callbacks and promises in vanilla JavaScript. In fact, the Observable will be added to future versions of JavaScript, but until that happens it is implemented in Angular with the help of the RxJS library.

Observables are widely used in Angular for handling asynchronous code. For example, to work with Ajax, when listening to events and navigating between the pages of an application (routing). To understand why we need to use asynchronous code instead of plain JavaScript, think about a code that waits for a response from a remote server. There is no way of knowing when the response will return, and whether it will ever come back, so it is not a good idea to stop executing the script until the response is received. Asynchronous code is a much better solution, and the way Angular prefers to handle asynchronous code is through observables.

# How Observable works in Angular?

The observable behavior follows the programming pattern of an observer which has two main players:

  1. Observable
  2. Observer

The Observable sends data while the Observer subscribes to it to receive the data.

The Observable fires the data in response to an event. For example, when a user clicks a button or in response to data that is received from a remote server.

On the other hand, the Observer has three handles to use the data that it receives:

  • onNext handles the requested data
  • onError to handle errors
  • onComplete which is used when the process ends

How observable works in Angular?

When you write an Observer you can decide what to do when you get back the requested data, how to behave in case of an error, and what to do if the code has finished running.


# Conclusion

An important example of Observable is the HttpClient module, which handles AJAX in Angular, as you can see in the series of tutorials that demonstrates the pattern by developing an Angular application with a PHP backend.

comments powered by Disqus