Resolve<T> – fetching and resolving data before routing

The reason for using this hook is so we can delay the routing to happen after we have fetched all the necessary data. You should not have anything long-running happening though. A more real case is that you have navigated to a product route, such as /products/114, and want to look up in the database what that product is and provide that to the route. 

You'll need the following to implement this:

  • Implement the Resolve<T> interface
  • Return a Promise from the resolve() method
  • Set the service as a provider to the module
  • Set the service in the resolve property of the route it is providing data to

Let's implement said service:

@Injectable()
export class ProductResolver implement Resolve<Product> {
constructor(
private http:Http,
private service: DataService,
private router:Router
) {}

resolve(route: ActivatedRouteSnapshot) {
let id = route.paramMap.get('id');
return this.service.getProduct( id ).then( data => {
if(data) {
return data;
}

else {
this.router.navigate(['/products']);
}

}, error => { this.router.navigate(['/errorPage']) });
}
}

// product.service.ts
export class DataService {
getProduct(id) {
return http.get(`/products/${id}`)
.map( r => r.json )
.map(mapProduct)
.toPromise()
}
}

At this point, we have implemented the Resolve<T> interface and we also ensure that a Promise is returned from the resolve() method. We also have some logic saying we will redirect the user if the data we get back is not what we expect or if an error happens. 

As a next step, we need to add the service to the providers keyword of our module:

@NgModule({
...
providers: [ProductResolver]
...
})

For the last step, we need to add the service to the route:

{
path: 'products/:id',
resolve: [ProductResolver],
component: ProductDetail
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset