Reading list Switch to dark mode

    Implementation/Uses of Resolvers in Angular Js

    Updated 16 January 2022

    Today we are going to learn Resover in Angular Js.

    Sometimes we need that data needed in our page must be retrieved before page navigation. in this case, we can use route resolver for prefetch the data needed before nevigation.

    Using Angular Resolvers, application can prefetch data from the server before the activatedRoute is activated of the next component.

    To resolve data before page navigation classes have to implement Resolve Interface.

    Start your headless eCommerce
    now.
    Find out More
    interface Resolve<T> {
      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T
    }

    Below is the code how a class can implement the Resolve interface and return the data to be fetched before route navigation.

    @Injectable({ providedIn: 'root' })
    export class HeroResolver implements Resolve<Hero> {
      constructor(private service: HeroService) {}
    
      resolve(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
      ): Observable<any>|Promise<any>|any {
        return this.service.getHero(route.paramMap.get('id'));
      }
    }

    Now Let’s understand the use of resolver with an example and step by step process.

    Suppose we have to create a component and we need that list of countries in that component and we have to prefetch the list and we will resolve the data through route resolver.

    Below is the module.ts file for our example.

    # myapp.module.ts

    // myapp.module.ts
    
    import { NgModule } from '@angular/core';
    import { MyAppRoutingModule } from './myapp-routing.module';
    import { MyAppComponent }     from './myapp.component';
    
    @NgModule({
        imports: [
            MyAppRoutingModule
        ],
        exports: [],
        declarations: [MyAppComponent],
        providers: [],
    })
    
    export class MyAppModule { }

    Create A Service (core.service.ts)

    Create a core service to get list of countries. We will use the list of country in our components.

    below is the code for service.

    //core.service.ts
    
    import { Injectable } from '@angular/core';
    import { Response }   from '@angular/http';
    import { HttpService }  from '../../http.service';
    
    @Injectable()
    export class CoreService {
        constructor(private http: HttpService) { }
    
        // This function will return the list of countries
        getCountries() {
            return this.http.get(`/api/admin/countries`)
                .map((response: Response) => response.json());
        }
    }

    Create the resolver file (country.resolver.ts)

    Second step to create the resolver file country.resolver.ts To resolve data before page navigation.
    Lets create a resolver which will prefetch data(country list) from the core.service.ts

    // country.resolver.ts
    
    import { Injectable } from '@angular/core';
    import { Response } from '@angular/http';
    import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { CoreService }  from './core.service';
    
    @Injectable()
    export class CountryResolver implements Resolve<any> {
        constructor(
            private core: CoreService
        ) {}
    
        resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
            return this.core.getCountries()
                .map(countries => {
                    return countries;
                })
                .catch((error: Response) => {
                    return Observable.throw(error);
                })
        }
    }

    So now we have created the resolver file.

    Now as we have completed the steps till creating resolver. Now we will move to the steps to use resolver in our components.

    Create Route Configuration (myapp-routing.module.ts)

    We will configure the routes. Lets modify the routes in the app-routing.module.ts

    // myapp-routing.module.ts
    
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    
    import { CountryResolver }   from '../../core/country.resolver';
    import { MyAppComponent }    from './myapp.component';
    
    const routes: Routes = [
      {
        path: 'add-entity',
        component: MyAppComponent,
        data: {'title' : "Add Entity"},
        resolve: {
          'countries': CountryResolver
        }
      },
      {
        path: 'edit-entity/:id',
        component: MyAppComponent,
        data: {'title' : "Edit Entity"} ,
        resolve: {
          'countries': CountryResolver
        }
      },
    ];
    
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule],
    })
    
    export class MyAppRoutingModule { }

    Create Component (myapp.component.ts)

    Now lets create a component in which we will use the data from the resolver. So we will get the data from the CountryResolver and assign to a variable from our component.

    // myapp.component.ts
    
    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute, Params } from '@angular/router';
    
    @Component({
        templateUrl: './myapp.component.html',
        styleUrls: ['../myapp.component.css']
    })
    
    export class MyAppComponent implements OnInit {
        countries: any = {};
    
        constructor(
            private route: ActivatedRoute,
            private router: Router
        ) {
          // write code for the constructor of your component
        }
    
        ngOnInit() {
            // below is how you can get the data from the resolver data
            this.route.data
            .subscribe((data: { countries: any }) => {
                this.countries = data.countries;
            });
        }
    
        // write code for your component
        .....
    }

    So in the ngOnInit() event we get the data from the route resolver and assigned the list of countries to one of our component class variable.

    Now you can use this variable containing the list of countries in your component and as per you requirement.

    So this is the process how you can create route revolvers in angular and use them. So you can use the same resolver in the multiple component where ever you find the use of the resolver.

    Hope after this blog, You will be able to use resolvers in your code easily.

    Thanks for reading. Happy coding. 🙂

    . . .

    Leave a Comment

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


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home