What is Observables in angular?

What is Observables in angular?

The result of the​​ Http.get​​ method is an Observable<Response> object, which is an example of an observable. Observables are part of a library called​​ Reactive Extensions, produced by Microsoft, which is used by Angular to connect different parts of the application. For the most part, you don’t work directly with observables in an Angular application because they are used behind the scenes, but one exception is when you need to introduce data into the application, such as from a web service.

An observable represents an item of work that will be performed asynchronously and produce a result at some point in the future, loosely equivalent to a .NET Task. The Observable<Response> result returned by the​​ Http.get​​ method, for example, represents an asynchronous activity that will produce a Response object when it is complete. The Response class is defined in the @angular/http module and is used by Angular to represent a response from an HTTP server.

The subscribe method is used to invoke a function when the work represented by the Observable has completed. The function receives the Observable result, which is a Response object in this case, and I use the Response.json method to parse the JSON data sent by the web service and assign it to the product​​ property, like this:

getProduct(id: number) {

 ​​ ​​ ​​​​ this.http.get("/api/products/" + id)

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ .subscribe(response => this.product = response.json());



The overall effect is that when a new instance of the Repository class is created, the constructor calls the getProduct method, which sends an HTTP request to the web service and uses the JSON data received in response to set the product property, which can be accessed by the rest of the application.

(Visited 16 times, 1 visits today)

Leave a Reply

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