Resolver In Angular

Introduction

 
Today we are going to check out an awesome functionality provided by angular named Resolver.  As per Angular documentation, we can see that it has been explained in a short manner, so, let's read what they have written between the lines. I will try to explain in simple words... Let's start! 
 

Why do we need Resolver?

 
Suppose you are building an awesome app where you load fetch, update, insert, and delete data from backend off course through the API services. Many times, we need to pass the data between two routes, or it may be the case that our 'Y' component needs data that is loaded by the 'X' component.
 
In simple words, you have a cake shop app and you want to load all the cakes from the backend or from some other component.
 
In all the above scenarios, if you have not made any special adjustment for data loading, you will face error/warning in the browser, as shown below. 
 
Resolver In Angular
 
In the above case, I have cakeStockID as a defined property in Model. 
 
The reason behind this is it doesn't get the data before rendering the HTML. i.e. our HTML loads before fetching data from the back end. 
 
This situation can be eliminated in different ways, but we have a Resolve interface provided by angular.
 
So to handle this situation we will wait for the data to be load and then proceed further. Let's do it by the resolver.
 
Our steps will be:
 
Create a Resolver ====> give that resolver object while routing ====> fetch loaded data via resolver in constructor of consuming constructor.
 
My scenario: I want to load all the cakes from the backend via resolver.
 
Step 1
 
Let's create a standalone component for the resolver, as shown below:
  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     Resolve,  
  6.     ActivatedRouteSnapshot,  
  7.     RouterStateSnapshot  
  8. } from '@angular/router';  
  9. import {  
  10.     showcaseCakesModel  
  11. } from '../rollin-shared/showcase-cakes.model';  
  12. import {  
  13.     rollinDataStorageService  
  14. } from '../Services/rollin-datastorage';  
  15. import {  
  16.     Observable  
  17. } from 'rxjs'  
  18. @Injectable({  
  19.     providedIn: 'root'  
  20. })  
  21. export class dataResolverService implements Resolve < showcaseCakesModel[] > {  
  22.     constructor(private svcObj: rollinDataStorageService) {}  
  23.     resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable < showcaseCakesModel[] > | showcaseCakesModel[] {  
  24.         return this.svcObj.get();  
  25.     }  
  26. }  
svcObject is my service object from where I am fetching the data.
 
So here, we are calling our get method. Ultimately, we want this data to be loaded as soon as we load the component. 
 
Step 2
 
There is a way to tell Angular, 'Hey buddy! I want to load this data first via resolver whenever the 'XYZ' component is loaded.' For that, we need to mention this resolver name as a parameter in routing, as shown below.
 
In my scenario: I want to load all the cakes from backend via resolver in ViewAllCakeComponent.
  1. import { dataResolverService } from './rollin-cakes/data-resolver';  
  2.   
  3. const rollinRoute: Routes=[    
  4.     {path:'',component:RollinAppComponent,pathMatch:'full',resolve:{data:dataResolverService}},    
  5.     {path:'view-allcakes',component:ViewAllcakesComponent,pathMatch:'full',resolve:{data:dataResolverService}}    
  6.  ]    
Here, we are giving 'data' as a key to retrieve the loaded data by the resolver. You can give it any other name also.
 
Step 3
 
So, all good until now!  Let's use this in our component where we want to load data before anything. To do that, we need to inject this resolver in the component.
 
In the constructor, it self-retrieves data loaded by the resolver from ActivatedRoute, as shown below.
 
This is quite relatable. If you look at resolve interface carefully, you will find its first parameter is ActivtedRouterSnapshot..
  1. import { Component, OnInit, DoCheck } from '@angular/core';    
  2. import { cakesTransactionService } from '../cake-transactions';    
  3. import { showcaseCakesModel } from 'src/app/rollin-shared/showcase-cakes.model';    
  4. import { rollinDataStorageService } from 'src/app/Services/rollin-datastorage';    
  5. import { Router, ActivatedRoute } from '@angular/router';    
  6.     
  7. @Component({    
  8.   selector: 'app-view-allcakes',    
  9.   templateUrl: './view-allcakes.component.html',    
  10.   styleUrls: ['./view-allcakes.component.css']    
  11. })    
  12. export class ViewAllcakesComponent implements OnInit {    
  13.   displayCakes:showcaseCakesModel[];    
  14.     
  15.   constructor(private route:Router,    
  16.               private actRoute:ActivatedRoute,     
  17.               private cakeObj:rollinDataStorageService,    
  18.               private cakeTransactionServiceObj:cakesTransactionService) {     
  19.     //console.log("called Constructor")    
  20.     
  21.     this.displayCakes= this.actRoute.snapshot.data['data'];    
  22.     
  23.     //console.log( this.displayCakes);    
  24.   }      
  25.   ngOnInit(): void {  
  26.   }      
  27. }   
It's done! Now going forwards, whenever this component is called, this data will be ready for us!