{"id":784,"date":"2022-04-07T08:17:00","date_gmt":"2022-04-07T08:17:00","guid":{"rendered":"https:\/\/staging.infragistics.com\/blogs\/?p=784"},"modified":"2025-02-18T12:35:21","modified_gmt":"2025-02-18T12:35:21","slug":"angular-observable-vs-angular-promise","status":"publish","type":"post","link":"https:\/\/www.infragistics.com\/blogs\/angular-observable-vs-angular-promise","title":{"rendered":"Angular Observable vs Angular Promise: Differences, Uses &amp; How To Build Them"},"content":{"rendered":"\n<p>When it comes to Angular, there are two main types of data management: using Observables or Promises with both being capable of managing asynchronous code in JavaScript. At first glance, Observables are seen as a more advanced alternative to Promises. But, in fact, they are quite different. From having separate APIs, through having different motives, to offering distinct ways for handling the async model in JavaScript, Angular Observables and Angular Promises have their own powers.<\/p>\n\n\n\n<p>How to know which one is right for your Angular project? Let\u2019s discuss them in detail, compare each implementation, and see the functions, advantages, and disadvantages. On top of this, I will demonstrate how to use Angular Observables and Angular Promises with our <a href=\"https:\/\/www.appbuilder.dev\/platform\" rel=\"noopener\">low-code App Builder<\/a><sup>\u00a0<\/sup>so you can handle asynchronous events easily and quickly.<\/p>\n\n\n\n<p class=\"text--align-center\"><a class=\"trackBlogCTA ui-btn ui-btn--default ui-btn--sm\" title=\"Button \/ Ignite UI for Angular \/ Try It Now\" href=\"\/products\/ignite-ui-angular\/download\">Try Ignite UI for Angular<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h8sl1orww0f6m72wm126d0h53ftzc4\">What Is Promise in Angular?<\/h2>\n\n\n\n<p>Promises in <a href=\"\/products\/ignite-ui-angular\">Angular<\/a> provide an easy way to execute asynchronous functions that use callbacks while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API. Then, the controller (or the directive) takes over, registering up to three callbacks\u2014success, error, and\/or notifications.<\/p>\n\n\n\n<p>There are four states of the Angular Promise:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>fulfilled &#8211; action is fulfilled<\/li>\n\n\n\n<li>rejected &#8211; action failed<\/li>\n\n\n\n<li>pending &#8211; action hasn\u2019t succeeded or failed yet<\/li>\n\n\n\n<li>settled &#8211; action is either fulfilled or rejected<\/li>\n<\/ul>\n\n\n\n<p>Something to remember is that Angular Promise is more passive compared to the Observable and cannot be canceled&nbsp;once it is started. In other words, when you pass the callback\u202fto the\u202fPromise\u202fconstructor (controller or directive), it will either resolve or reject the function.<\/p>\n\n\n\n<p>Now, there are several disadvantages to the Angular Promise.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Promises aren\u2019t cancellable, and you have to wait until the callback returns an error or success.<\/li>\n\n\n\n<li>Not suitable for centralized and predictable error handling as errors are sent to the child promise.<\/li>\n\n\n\n<li>They don\u2019t provide any operations.<\/li>\n\n\n\n<li>Promises execute an async value only once.<\/li>\n\n\n\n<li>It cannot be used for multiple values over time.<\/li>\n\n\n\n<li>They become hard to manage with larger applications.<\/li>\n\n\n\n<li>They cannot be retried.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h14sl1orx10773lnhri9u5n719noe0p\">How To Create Promises in Angular?<\/h3>\n\n\n\n<p>To create a promise in Angular we just need to use &#8216;new Promise(function)&#8217; syntax. The promise constructor takes function as a parameter and that inner function takes resolve and reject as a params.<\/p>\n\n\n\n<p>Let\u2019s see how this looks in the code snippet below.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"http:\/\/static.infragistics.com\/marketing\/Blogs\/Migration\/00\/00\/00\/09\/43\/8272.creating-angular-promice-screenshot_6.png\" alt=\"creating angular promise code snippet logic\" title=\"creating angular promise code snippet logic\"\/><\/figure>\n\n\n\n<p>Now that we know how to create an Angular Promise, we will use it to implement a very simple scenario. The created Promise will help us validate whether the number is prime or not.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"http:\/\/static.infragistics.com\/marketing\/Blogs\/Migration\/00\/00\/00\/09\/43\/8272.creating-angular-promice-screenshot_9.png\" alt=\"angular observable vs angular promise\" title=\"creating promise in angular code snippet\"\/><\/figure>\n\n\n\n<p>And finally, to put our method in use, we will handle the Promise in the following way.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"http:\/\/static.infragistics.com\/marketing\/Blogs\/Migration\/00\/00\/00\/09\/43\/2806.creating-angular-promice-screenshot_8.png\" alt=\"completion of angular promise creations code snippet\" title=\"completion of angular promise creations code snippet\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h19sl1orx5vw4xs67i1usq50ddoh6zk\">What Is Observable in Angular?<\/h2>\n\n\n\n<p>Observables provide more capabilities as they let developers run functions asynchronously and synchronously. They represent a stream of values that can handle 0, 1, or multiple events, using the same API for each. What I personally like about Angular Observables is the number of operators that simplify coding, including retry(), \u202freplay(), map,\u202fforEach,\u202freduce, and more.<\/p>\n\n\n\n<p>Just like Angular Promises, Observables in Angular also have their disadvantages.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Observables aren\u2019t natively supported by browsers.<\/li>\n\n\n\n<li>They require RxJS operators to get a new tailored stream of values.<\/li>\n\n\n\n<li>Debugging the code with observables may be a bit more challenging.<\/li>\n\n\n\n<li>You must have the know-how of extra tools and techniques to test the RxJS code.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h23sl1orxbsy1543y1r1i0y89g1cdlv5d\">How To Create Observables in Angular?<\/h3>\n\n\n\n<p>To create an Observable in Angular, first, it is necessary to import Observable from rxjs because, as we learned above, they are not natively supported.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"http:\/\/static.infragistics.com\/marketing\/Blogs\/Migration\/00\/00\/00\/09\/43\/2806.creating-angular-oservable-screenshot-11.png\" alt=\"importing angular observable\" title=\"importing angular observable\"\/><\/figure>\n\n\n\n<p>To create a new Observable we just need to use its constructor and to add the logic that will be executed upon subscription. In our case we will create an Observable that will return a great data source for our <a href=\"\/products\/ignite-ui-angular\/angular\/components\/grid\/grid\">Angular grid <\/a>component.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"http:\/\/static.infragistics.com\/marketing\/Blogs\/Migration\/00\/00\/00\/09\/43\/1348.creating-angular-oservable-Screenshot_13.png\" alt=\" getting data angular observable\" title=\"getting data angular observable\"\/><\/figure>\n\n\n\n<p>After that what is left for us is to subscribe to the created Observable and bind the received data as a data source to our <a href=\"\/products\/ignite-ui-angular\">Angular components<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"http:\/\/static.infragistics.com\/marketing\/Blogs\/Migration\/00\/00\/00\/09\/43\/7776.creating-angular-oservable-Screenshot_14.png\" alt=\"getting data angular observable\" title=\"getting data angular observable\"\/><\/figure>\n\n\n\n<p>A great and more meaningful example of a use case for working with observables is using IgxGrid with Remote Data. As you can see in the example, only a small chunk of data is fetched initially when the component is rendered and on each scroll or data operation that is performed a new piece of the data is taken. This observable of type any[] is binded directly to the grid using async Angular pipe. The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"http:\/\/static.infragistics.com\/marketing\/Blogs\/Migration\/00\/00\/00\/09\/43\/7776.angular-remote-data-operations-demo.png\" alt=\"angular remote data operations demo\" title=\"angular remote data operations demo\"\/><\/figure>\n\n\n\n<p><a href=\"\/products\/ignite-ui-angular\/angular\/components\/grid\/remote-data-operations#remote-virtualization-demo\">Click here to see the sample<\/a> and inspect the code right away.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h26sl1orxkfq1l0qfq11jtnw3t1uh9ec5\">How To Use Angular Observable and Promise in App Builder?<\/h2>\n\n\n\n<p>As we understand from the written above the most common scenario to use Observables is when we need to bind data to some component. To fetch data, we must make HTTP request using HttpClient. The best way to do it is to carry it out into a separate service. All HttpClient methods return an RxJS Observable of something. In general, an Observable can return multiple values over time but an Observable from HttpClient always emits a single value and then completes, never to emit again.<\/p>\n\n\n\n<p>In the App Builder, binding a component to a data source is easy and intuitive. You currently have the following options to choose from in order to use one of our predefined data sources:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Upload a JSON file or add a URL to a JSON file that contains your data.<\/li>\n\n\n\n<li>Add\/upload a <a href=\"https:\/\/www.appbuilder.dev\/blog\/app-builder-release-with-swagger-support\" rel=\"noopener\">Swagger<\/a> definition file that describes all of your server&#8217;s endpoints. You can then directly get your real data from there.<\/li>\n<\/ul>\n\n\n\n<p>After that, no matter which approach you choose, you can use the Data drop-down from our props panel to bind the data to the component &#8211; for example, to the Angular grid.<\/p>\n\n\n\n<p>Now we can look at the <a href=\"https:\/\/www.appbuilder.dev\/blog\/angular-code-generation\" rel=\"noopener\">generated code in Angular.<\/a> We give you a separate service where the data fetching is performed using HTTP get method.<\/p>\n\n\n\n<p>And you can see in the MasterViewComponent ts file the subscription the data service performed. With this basis, you can conduct even more complicated scenarios whenever necessary.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h28sl1orxqws17owpyd17mk1fh2qs2z7\">Angular Observable vs Promise: What\u2019s the Difference?<\/h2>\n\n\n\n<p>To present the differences between Observables and Promises in Angular, I decided to compose a table. This way you will be able to compare them in a more digestible and super concise way.<\/p>\n\n\n\n<p>&nbsp;<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><td>\n<p><strong>ANGULAR OBSERVABLES<\/strong><\/p>\n<\/td><td>\n<p><strong>ANGULAR PROMISES<\/strong><\/p>\n<\/td><\/tr><tr><td>\n<p>Can handle both synchronous and asynchronous events<\/p>\n<\/td><td>\n<p>Can only handle asynchronous data returns<\/p>\n<\/td><\/tr><tr><td>\n<p>Emit and complete 0, 1, or multiple values over a period of time (stream data in multiple pipeline)<\/p>\n<\/td><td>\n<p>Only emit one value at a time (have one pipeline)<\/p>\n<\/td><\/tr><tr><td>\n<p>Less passive, meaning<\/p>\n<\/td><td>\n<p>More passive, meaning<\/p>\n<\/td><\/tr><tr><td>\n<p>Offer operations like map, filter, reduce, retry(), or\u202freplay(), map,\u202fforEach, and more<\/p>\n<\/td><td>\n<p>Do not provide operators<\/p>\n<\/td><\/tr><tr><td>\n<p>Are cancellable, using the unsubscribe() method, meaning the listener doesn\u2019t receive further values\u202f<\/p>\n<\/td><td>\n<p>Are not cancellable<\/p>\n<\/td><\/tr><tr><td>\n<p>Are lazy, i.e., the producer function triggers after users subscribe to the stream\u202f<\/p>\n<\/td><td>\n<p>Are eager, i.e., the Promise callback executes immediately and only once at the moment of its definition, without .then and .catch\u202f<\/p>\n<\/td><\/tr><tr><td>\n<p>Subscribers handle errors<\/p>\n<\/td><td>\n<p>Push errors to the child Promises<\/p>\n<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Apparently, in the Angular Observable vs Promise comparison, the Observable wins. So, is there a good reason to use Promise, then? Absolutely.<\/p>\n\n\n\n<p>Firstly, Observables come at a certain cost. As I mentioned before, they are not natively supported by browsers. Which means you must implement the RxJS library. And while it helps you create asynchronous or callback-based code, its bundle size can exceed\u202f17.4kb.<\/p>\n\n\n\n<p>Secondly, when your <a href=\"https:\/\/medium.com\/ignite-ui\/how-to-create-angular-app-from-scratch-in-10-minutes-infragistics-blog-fcd98c8b1b9c\" rel=\"noopener\">Angular app<\/a> is asynchronous by default, there\u2019s no better way to handle all asynchronous functions and events than using Angular Promise. Isn\u2019t that right?<\/p>\n\n\n\n<p>Next, if you don\u2019t want to use reactive style or don\u2019t care about streams of values and cancellable events, then go for Promises in Angular.<\/p>\n\n\n\n<p>On a final note, we recently published an extremely detailed and helpful Angular UI Data Grid tutorial\u202fto help you\u202flearn how to\u202fcreate a full-featured <a href=\"\/products\/ignite-ui-angular\/angular\/components\/grid\/grid\">Angular UI Grid<\/a> from scratch. So, you might want to check it out as well. Click below.<\/p>\n\n\n\n<iframe width=\"100%\" height=\"475\" src=\"https:\/\/www.youtube.com\/embed\/Xv_fQVQ8fmM?si=T8C2qhzKrzQsl12n\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n\n\n\n<figure class=\"wp-block-image pt-4\"><a href=\"\/products\/ignite-ui-angular\/download\"><img decoding=\"async\" src=\"https:\/\/static.infragistics.com\/marketing\/Blog-in-content-ads\/Ignite-UI-Angular\/ignite-ui-angular-you-get-ad.gif\" alt=\"Ignite UI for Angular benefits\" title=\"Ignite UI for Angular benefits\"\/><\/a><\/figure>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are two main ways for managing asynchronous code in JavaScript &#8211; using Angular Observable or Angular Promise. But what is the difference between them and how to build Observables and Promises? Read more.<\/p>\n","protected":false},"author":60,"featured_media":1017,"comment_status":"publish","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-784","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-angular"],"_links":{"self":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/784","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/users\/60"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/comments?post=784"}],"version-history":[{"count":14,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/784\/revisions"}],"predecessor-version":[{"id":1854,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/784\/revisions\/1854"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media\/1017"}],"wp:attachment":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media?parent=784"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/categories?post=784"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/tags?post=784"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}