Angular 7 | Angular Data Services using Observable
Observable manage async data and a few other useful patterns. Observables are similar to Promises but with a few key differences. Unlike Promises, Observables emit multiple values over time. In real scenarios, web socket or real-time based data or event handlers can emit multiple values over any given time. In such a case Observables are the best option to use.
In angular, Observables are one of the most used techniques and is used extensively in integration with Data Services to read a REST API. Other than that, to access an observable, the component first needs to subscribe to the Observable. It is important to do this to access the data in observable REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing the web services simply and flexibly without having any processing. To read more you can navigate to this link.
Services are used to create variables/data that can be shared and can be used outside the component in which it is defined. A service can be used by any component and thus it acts as a common data point from which data can be distributed to any component in the application. To read more about services follow this link.
To add a service write the following command in the console.
ng g s ServiceName OR ng generate service ServiceName
This is a small example of a service named Data in which an event happening in the component will trigger the method of the service.
The data.service.ts code
The app.component.ts code
Services With Observable:
In combination, it is famous to work with REST API. In the following example there will be a Service in which an API will be accessed using GET request feature provided in the HttpClientModule in Angular, which in turn returns an observable. This observable will be subscribed by a component of the application and then shown on the page.
The Directives Used in Html of RegUserComponent
To run this application migrate inside the project and run the following command.
cd < Project Path > ng serve -o
Please Login to comment...