DEV Community

Cover image for Angular Resolver: A core tutorial for beginners
ArohiAdhyaru
ArohiAdhyaru

Posted on

Angular Resolver: A core tutorial for beginners

The fundamental purpose of an angular resolver is to prefetch data even before the user begins to browse it. One option for handling data retrieval and presentation from an API is to route a user to a component and then call a function in a class in a certain component's ngOnInit hook to obtain the required data. Perhaps the component can display a loading indicator when retrieving the data.

Another approach is to employ a route resolver, that enables you to gather information before choosing the new path.

The Hacker News API is considered one of the most accessible APIs. This is a website where links can be shared and discussed. The most popular posts can be retrieved via the API, and details about specific posts can be shown.
You will construct a route resolver in this article that queries the Hacker News API for data before directing users to the route that shows the data collected.

Prerequisites

The Hacker News API is one of the accessible APIs. A website where links can be shared and discussed is called Hacker News. The most popular posts can be retrieved via the API, and details about specific posts can be shown.
You will construct a route resolver in this article that queries the Hacker News API for data before directing users to the route that shows the data collected.

General Routing Flow is as follows.

  1. The user selects the link.
  2. The relevant component is loaded by Angular.
  3. Let's use Resolver to comprehend the Routing Process now.
  4. The user selects the link.
  5. Angular run certain code and produces a value or observable as a result.
  6. The class of the element that is certain to load can contain the function Object() { [native code] }, ngOnInit, or observable where you can collect the returned value.
  7. Use the data that was gathered for your intended use. Your component can now be loaded.

Further steps are done with Angular Resolver.

Creating the project

We will construct from a standard Angular project created with @angular/cli for the purposes of this guide.

npx @angular/cli new angular-route-resolvers-example --style=css --routing --skip-tests
Enter fullscreen mode Exit fullscreen mode

This will build up a new Angular project with routing turned on, tests skipped, and layouts set to "CSS" rather than "Sass, Less, or Stylus".

Now navigate to the project directory that was just created:

cd angular-route-resolvers-example
Enter fullscreen mode Exit fullscreen mode

At this point, we have initiated a brand new Angular project with @angular/router.

Building a Resolver

Let's begin by creating a resolver that, after a fixed interval of time interval, delivers a string. The exploration of the foundations of wire pathways that can be utilized in larger projects can be aided by this modest preliminary proof of concept.

To begin with, make a unique class for such resolver in a specific folder:

./node_modules/@angular/cli/bin/ng generate resolver news

This will use the @angular/cli to generate a resolver named news:

Configuring Routes

In order to experience two different routes, we will require another set of new components. Here, the landing page will be the home

First, use @angular/cli to generate a home component:
./node_modules/@angular/cli/bin/ng generate component home

Then, use @angular/cli to generate a top component:

./node_modules/@angular/cli/bin/ng generate component top

Accessing the Resolved Data in the Component

In the component, one can use the data property in order to get access the resolved access the resolved data using the data property of ActivatedRoute’s snapshot object:

src/app/top/top.component.ts

import { Component, OnInit } from '@angular/core';

import { ActivatedRoute } from '@angular/router';

@Component({ ... })
export class TopComponent implements OnInit {
  data: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.data = this.route.snapshot.data;
  }
}

Enter fullscreen mode Exit fullscreen mode

Now, in the component, you can access the Route!

Resolving Data from an API

In order to make things more practical by getting data from an API. In this part of the process, you will create a service that gets data from the Hacker News API.

Further, we will use HttpClient to request the endpoint.
For the first step, add the HttpClientModule to

`app.module.ts`

`src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
`
Enter fullscreen mode Exit fullscreen mode

Accessing Route Parameters

You can access the current route parameters in your resolver utilizing the ActivatedRouteSnapshot object.

Here’s an illustration where you would use a resolver to get access to the id param of the current route.

First, use the @angular/cli to generate a resolver named post:

./node_modules/@angular/cli/bin/ng generate resolver news

Then, modify post.resolver.ts to use ActivatedRouteSnapshot:

For the next process, add a getPost method to NewsService ​​And add PostResolver and the post/:id route to app-routing.module.ts

Handling Errors

When the error occurs while fetching the data, you could catch and deal with the error in the resolver using RxJS’s catch operator. You should expect something like this as demonstrated below:

src/app/news.resolver.ts
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';

import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';

import { NewsService } from './news.service';

@Injectable()
export class NewsResolver implements Resolve<any> {
  constructor(private newsService: NewsService) {}

  resolve(): Observable<any> {
    return this.newsService.getTopPosts().pipe(catchError(() => {
      return of('data not available at this time');
    }));
  }
}`
Enter fullscreen mode Exit fullscreen mode

Or you could return an EMPTY observable and return the user to the root path:

Conclusion:

In this tutorial for beginners, I implemented a route resolver that gets data from the Hacker News API before navigating to a route that displayed the gathered data. This process may seem a bit overwhelming however, in reality, it is no distinct than a simple process like a normal integration with any third-party app.

Hire Angularjs Developer and make the journey of Angularjs Development easier for your project. Transform your product from the basic to the pro level and get the best Angular Developers for your project!

Top comments (1)

Collapse
 
dmondev profile image
dmondev

Nice article, @arohiadhyaru !
I never found resolvers to be particularly useful. If the api takes a while to respond, you'll be in a blank/loading page state while waiting. Is there a use case other than that, or a way of using resolvers that wouldn't suffer from this issue ?

Cheers !