Http and Observables in Angular
2 min readJul 25, 2022
- To fetch the data in angular, we can use observables with http to fetch data.
- An angular application will use http via a GET request to fetch data from a back-end server.
- The back-end could be powered by any number of server-side technologies such as java, php, python, or even server- side javascript in the form of Node.js
- An http response is sent from the back-end web service to the client side angular application.
Observables and Reactive Extensions:-
- Reactive extensions ,or RxJS, represent a data sequence as an Observable Sequence.
- The observable sequence is simply referred to as an Observable.
- The purpose of an observable is to manage asynchronous data, such as what you might get when waiting for data to arrive over a network using HTTP.
- An observable treats events as a collection.
- One way to think of an observable is that of an array whose items populate asynchronously over time.
- In an Observable, you would have a method that subscribes to receive notifications as a new data arrives.
- The angular framework uses Observables to do its asynchronous work.
Angular Observables:-
- Observable offer significant benefits over other techniques for event handling, asynchronous programming , and handling multiple values.
- Observables are declarative- that is , you define a function for publishing values, but it is not executed until a consumer subscriber to it.
Technical Details of Observables and HTTP Requests in Angular:-
Setting up HTTP in Angular:-
- Add HttpClientModule to the imports array of one of the applications Angular Modules.
- Import what is needed for the data service.
- Define a dependency for the Http client service using the constructor.
- Create a method for each http request type you would like to use.
- Call the http method as needed. (Eg:- GET,POST)
- Use Generics to specify the return type.
Subscribing to Observables:-
- Call the subscribe method of the returned observable
- Create a function to handle emitted items.
- Assign property data to returned JSON object
- Create a function to handle errors.