Using Resolve -Promises in Angular 2 Http Services

Table of contents
Reading Time: 2 minutes

ResolveYou have a huge list of users that you have to show on one of the views in angular 2 app, you called the action to redirect to users list view and the page is blank because your HTTP service is still loading the list of users from the external API and until it grabs all the list it can’t show anything on the view, isn’t it the worst user experience?

Resolve is a powerful technique to achieve the best user-experience when browsing between pages in your app. It also makes the component’s code much cleaner in contrast to fetching data inside the component.

So in the routing of Angular 2, we can use the feature resolve, as we were using the angular 1.x as well. Here we have the same scenario we have two links on the root component that we are bootstrapping, one is dashboard and another is users, when we click the users tab we are calling a service that hits a service and get the data from that service earlier same scenario was happening, as soon as we click the link we were redirecting to the users tab and data was coming later, but now we are using resolve and by that we click the link and redirect touch the view when all the data is fetched from the server using that  API, because we are using the resolve and this is getting used in the routing of children route,

Code in routing:

and in the user-resolve.service.ts

and in app.service.ts where we are hitting the API for fetching the URL:


If you are not feeling good while using promises you can convert your app.service.ts HTTP call to return Observable instead toPromise(), so just remove .toPromise() from there like this:

Now Update your user-resolve.service.ts from then (it is used for promises) to subscribe (as we already know that we have to subscribe the Observable), like this:

This is using promise and we are giving promise, but as we know about callback, observables and promises are sometimes confusing so I will be writing the most basic post that will explain these terms with actual examples.
You can learn about “resolve” from their official documentation although here is not much about that, you can prefer scotch-school.

Here is the repo link of the source code: Knoldus Frontend Devs

Written by 

Rachel Jones is a Solutions Lead at Knoldus Inc. having more than 22 years of experience. Rachel likes to delve deeper into the field of AI(Artificial Intelligence) and deep learning. She loves challenges and motivating people, also loves to read novels by Dan Brown. Rachel has problem solving, management and leadership skills moreover, she is familiar with programming languages such as Java, Scala, C++ & Html.

1 thought on “Using Resolve -Promises in Angular 2 Http Services2 min read

Comments are closed.