Implement Resolver in Angular - lakshmansha/ngAngularPractices GitHub Wiki
Hi Friends, This is Lakshman here.
As part of the Series "Angular Best Practices".
Today, We will Implement Resolver for your angular app.
The pre-requisites are
- Node.JS - Click Here
- Angular CLI - Click Here
- VS Code - Click Here
- Creeate Resolver - Click Here
- Angular Snippets (Version 11) Click Here
For Code Editor its VS Code.
In Angular Application, every page requires some information to display it.
By Default, every developer call service to fetch some information to display in OnInit Function inside Component.
Most people forgot about Resolver itself. It helps our application to way better than you think.
Service & Resolver has to be like bread & butter to Solve Data dependencies on Page Load.
- By default, we have the option to Create Resolver via Angular-CLI after cli version 11.0.5 or greater.
- Add Angular Snippets from Extension Marketplace.
- Each Resolver can have only one resolve method.
- The Only thing to do is Use it.
- Create Resolver and map with routes in Routing.
- Add Resolver to Providers in Module.
To Create via Angular CLI Commands if CLI version is 11.0.5 or greater:
ng g resolver <your-module>/<your-resolver>
To Create Snippets Commands:
a - resolver;The Below code will be generated,
import { Injectable } from "@angular/core";
import { Resolve, ActivatedRouteSnapshot } from "@angular/router";
import { Observable } from "rxjs";
@Injectable({ providedIn: "root" })
export class YourResolver implements Resolve<any> {
resolve(route: ActivatedRouteSnapshot): Observable<any> | Promise<any> | any {
return;
}
}Replace the resolve method with below code:
constructor(private service: YourService) { }
resolve(route: ActivatedRouteSnapshot): Observable<any> | Promise<any> | any {
return forkJoin([
this.service.getService()
]).pipe(
map(allResponses => {
return {
List: allResponses[allResponses.length - 1]
};
})
);
}Then Add Your Resolver in .module.ts File.
import { YourResolver } from './hello.resolver';
...
@NgModule({
...
providers: [
YourResolver
]
...Add below Code on -routing.module.ts
const routes: Routes = [
{
path: "your",
component: YourComponent,
data: { title: "Your List Module" },
resolve: { responses: YourResolver },
},
];In Component to Consume the Data add the below code,
YourList: Your[] = [];
constructor(..., private route: ActivatedRoute) { }
ngOnInit(): void {
this.PageLoad();
}
PageLoad() {
this.YourList = this.route.snapshot.data.responses['List'];
}Once all the steps completed.
We can start using this resolver to Fetch the Data required to load the module.
That wrap up the Implementation process of Resolver in Angular
You may also access to source on GitHub by Click Here
On-road head, we will discuss a lot of things.
Looking forward to your comments and share your feedback.
Until that, I am Lakshman, Signing Off.