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.

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:
- import {
- Injectable
- } from '@angular/core';
- import {
- Resolve,
- ActivatedRouteSnapshot,
- RouterStateSnapshot
- } from '@angular/router';
- import {
- showcaseCakesModel
- } from '../rollin-shared/showcase-cakes.model';
- import {
- rollinDataStorageService
- } from '../Services/rollin-datastorage';
- import {
- Observable
- } from 'rxjs'
- @Injectable({
- providedIn: 'root'
- })
- export class dataResolverService implements Resolve < showcaseCakesModel[] > {
- constructor(private svcObj: rollinDataStorageService) {}
- resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable < showcaseCakesModel[] > | showcaseCakesModel[] {
- return this.svcObj.get();
- }
- }
Sagar PardeshiPosted Jun 25, 2020, 1:25 AM
Very good explore in this article use of Resolver...