Menu Home

Angular Routing: Displaying a spinner

Whilst working through Deborah Kurata’s superb Pluralsight Course on Angular Routing, in module 9 Styling, Animating, and Watching Routes, she mentions if you want the spinner to appear whilst the products are loaded for the product list page you can create a resolver.

In this post I show you how I created a resolver for the product-list route.

products-resolver.service.ts

This is a new service and using the existing products service it returns an observable of type Product array.

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { Observable } from 'rxjs';

import { Product } from './product';
import { ProductService } from './product.service';


@Injectable({
    providedIn: 'root'
})

export class ProductsResolver implements Resolve<Product[]> {

    constructor(private productService: ProductService) {}

    resolve(route: ActivatedRouteSnapshot, 
            state: RouterStateSnapshot): Observable<Product[]>{
                return this.productService.getProducts();
                
    }    
}

product.module.ts

This existing file contains the routing for the product functionality. Amend the empty or default path by adding the resolve object:

...
{ path: '', 
  component: ProductListComponent,
  resolve: { resolvedData: ProductsResolver }, 
},
...


resolvedData will be the name used to refer to the resolver and ProductsResolver is the name of the class created within the new products-resolver.service.ts

product-list.component.ts

The final change is to amend the the ngOnInit method of the product-list component so it uses the route resolver observable.

...
this.route.data.subscribe( data => {
      const resolvedData = data['resolvedData'];
      this.products = resolvedData;
      this.errorMessage = resolvedData.error;
      this.filteredProducts = this.performFilter(this.listFilter);
})

The Product array is retrieved from the resolver using its name resolvedData which is then assigned to the components Products array.

Result

When navigating to the Products list page the spinner is displayed

Acknowledgements

Thanks to Deborah Kurata for her superb course on Angular Routing.

Categories: Angular Typescript

oraclefrontovik

Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.