Tuesday 20 February 2018

Angular - Promises and Observables

Promise
Promises deal with one asynchronous event at a time.
In Angular we can use either Promises or Observables. By default the Angular Http service returns an Observable. To prove this, hover the mouse over the get() method of the Http service in any service.ts file. Notice from the intelligence, that it returns Observable[Response].
 To use Promises instead of Observables we will have to first make a change to the service to return a Promise instead of an Observable.

Observable
Observables can be defined as a streams of data whose items arrive asynchronously over time.
To use observables, Angular uses a third-party library called Reactive Extensions (RxJS). Observables are a proposed feature for ES 2016, the next version of JavaScript.

You can think of an observable as an array whose items arrive asynchronously over time. Observables help you manage asynchronous data, such as data coming from a backend service. Observables are used within Angular itself, including Angular’s event system and its http client service. To use observables, Angular uses a third-party library called Reactive Extensions (RxJS). 

Differences: 
In Angular, to work with asynchronous data we can use either Promises or Observable. There are several differences between Promises and Observables.
  • A Promise emits a single value where as an Observable emits multiple values over a period of time. You can think of an Observable like a stream which emits multiple items over a period of time and the same callback function is called for each item emitted. So with an Observable we can use the same API to handle asynchronous data whether that data is emitted as a single value or multiple values over a period of time.
  • A Promise is not lazy where as an Observable is Lazy. 
  • A Promise cannot be cancelled where as an Observable can be cancelled using the unsubscribe() method.
  • Observable provides operators like map, forEach, filter, reduce, retry, retryWhen etc.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives