Load All Data Before Loading The Component View In Angular 6

While working on the Angular live project, we use a real-world API and there might be some delay before the data to display is returned from the server and in that case, we don’t want to display a blank component to the users when waiting for the data. Router Resolve API helps us a lot to resolve this issue.

In the previous article, we have seen how to create modern page loader using Router Events in Angular 6. It’s nice to show a page loader when navigating one page/component to another page/component, but there are two main issues here,

  • The Component view is displayed before loading data is needed to display on that component view
  • Page loader completes its processing before the component view is loaded

We will see in this article how we can resolve these issues.

Load All Data Before Loading The Component View In Angular 6

While working on the Angular live project, we use a real-world API and there might be some delay before the data to display is returned from the server and in that case, we don’t want to display a blank component to the users when waiting for the data. Router Resolve API helps us a lot to resolve this issue.

Router Resolve API

It's preferable to pre-fetch data from the server so it's ready the moment the route is activated. This also allows you to handle errors before routing to the component.

Check the Angular official documentation here for more details.

In short, if you want to delay rendering the routed component until all necessary data to be displayed on this component is fetched from the server, Resolve API helps us.

Output

Application after applying the Resolve will work like below,

Load All Data Before Loading The Component View In Angular 6
 
Implementation

To implement the Resolve API in an Angular application, we need to import Resolve interface from @angular/router package, implement Resolve interface and implement the Resolve() method. This method can return a Promise or an Observable.

Let’s understand this powerful API with the help of the below example.

We will build an Angular application where we will call JSONPlaceHolder API to get post data and will show the data in the user-posts component. Here, we will make sure that my user-posts component will not load or display until all user posts data from API is ready to load or display.

Creating an Interface (post.interface.ts)
  1. export interface IPost {      
  2.       userId: string;  
  3.       id: number;  
  4.       title: string;  
  5.       body: string;  
  6. }  

Creating a service (post.service.ts) 

  1. import { Injectable } from "@angular/core";  
  2. import { HttpClient } from "@angular/common/http";  
  3. import { Observable } from "rxjs";  
  4. import { delay } from "rxjs/operators";  
  5. import { IPost } from "../post.interface.ts";  
  6.   
  7. @Injectable({  
  8.   providedIn: "root"  
  9. })  
  10. export class PostService {  
  11.   private url = "http://jsonplaceholder.typicode.com/posts";  
  12.   
  13.   constructor(private http: HttpClient) {}  
  14.   
  15.   getPosts(): Observable<IPost[]> {  
  16.     return this.http.get<IPost[]>(this.url).pipe(delay(1000));  
  17.   }  
  18. }  

Creating a Resolver (user-posts.resolve.ts) 

  1. import { Injectable } from "@angular/core";  
  2. import { Resolve, ActivatedRouteSnapshot } from "@angular/router";  
  3. import { Observable } from "rxjs";  
  4. import { PostService } from "./../services/post.service";  
  5. import { IPost } from "../post.interface.ts";  
  6.   
  7. @Injectable()  
  8. export class UserPostsResolve implements Resolve<IPost[]> {  
  9.   constructor(private postService: PostService) {}  
  10.   
  11.   resolve(route: ActivatedRouteSnapshot): Observable<IPost[]> {  
  12.     return this.postService.getPosts();  
  13.   }  
  14. }  

Registering Resolve in Routing module and Routing Configuration (app.module.ts)

Import this resolver in the app.module.ts (wherever your routing module and routing configuration exists. In my case, Routing configuration is defined in app module itself) and add a resolved object to the user-posts.component.ts route configuration.

  1. imports: [  
  2.     BrowserModule,  
  3.     HttpClientModule,  
  4.     FormsModule,  
  5.     RouterModule.forRoot([  
  6.       { path: '', component: HomeComponent },  
  7.       {   
  8.         path: 'userposts',          
  9.         component: UserPostsComponent,   
  10.         resolve:{         
  11.           userposts:UserPostsResolve  
  12.         }   
  13.       },  
  14.       { path: 'userposts/:id', component: UsrProfileComponent },  
  15.       { path: 'bloggers', component: BloggerComponent },  
  16.       { path: 'contact-us', component: ContactFormComponent },  
  17.       { path: '**', component: NotFoundComponent }  
  18.     ]),  
  19.     BrowserAnimationsModule,  
  20.     MaterialModule,  
  21.     SlimLoadingBarModule.forRoot()  
  22.   ],  
  23.   providers: [  
  24.     PostService,  
  25.     [{ provide: 'BASE_URL', useFactory: getBaseUrl() }],  
  26.     ScrollDatService,  
  27.     UserPostsResolve  
  28.   ],  

Creating a component

To create a user-posts component, use the following command.

ng g c UserPosts --module app

user-posts.component.ts 

  1. import { Component, OnInit } from "@angular/core";  
  2. import { ActivatedRoute } from "@angular/router";  
  3.   
  4. import { PostService } from "./../services/post.service";  
  5. import { IPost } from "../post.interface.ts";  
  6.   
  7. @Component({  
  8.   selector: "app-user-posts",  
  9.   templateUrl: "./user-posts.component.html",  
  10.   styleUrls: ["./user-posts.component.css"]  
  11. })  
  12. export class UserPostsComponent implements OnInit {  
  13.   userPosts: IPost[] = [];  
  14.   
  15.   postObject$;   
  16.   
  17.   constructor(  
  18.     private postService: PostService,  
  19.     private route: ActivatedRoute  
  20.   ) {}  
  21.   
  22.   ngOnInit() {  
  23.     this.userPosts = this.route.snapshot.data.userposts;   
  24.   }  
  25. }  

user-posts.component.html 

  1. <ul class="list-group">  
  2.   <li *ngFor="let post of userPosts" class="list-group-item">  
  3.     <button (click)="updatePost(post)" class="btn btn-default btn-sm">Update</button>  
  4.     <button (click)="deletePost(post)" class="btn btn-default btn-sm">Delete</button>  
  5.     <a [routerLink]="['/userposts',post.id]">{{post.id}}</a> - {{post.title}}  
  6.   </li>  
  7. </ul>  

As per the above code, when you navigate from home component to user posts component, you will see loading bar as running until component loads data and displays the component. Now, run your application and see how resolve API works.

Check the below post to help out with how page loader is implemented in the Angular application.

Summary

Through this article, we learned how to implement Resolve API in an Angular application.

Write to me in the comment box in case you need any help or you have any questions or concerns. Have a good day!