Resolve guard

A resolve guard is a type of a router guard, as mentioned in Chapter 9, Design Authentication and Authorization. A resolve guard can load necessary data for a component by reading record IDs from route parameters, asynchronously load the data and have it ready by the time the component activates and initializes.

The major advantages for a resolve guard includes reusability of loading logic, reduction of boilerplate code, and also shedding dependencies, because the component can receive the data it needs without having to import any service:

  1. Create a new user.resolve.ts class under user/user:
src/app/user/user/user.resolve.ts
import { Injectable } from '@angular/core'
import { Resolve, ActivatedRouteSnapshot } from '@angular/router'
import { UserService } from './user.service'
import { IUser } from './user'

@Injectable()
export class UserResolve implements Resolve<IUser> {
constructor(private userService: UserService) {}

resolve(route: ActivatedRouteSnapshot) {
return this.userService.getUser(route.paramMap.get('userId'))
}
}
  1. You can use a resolve guard as shown:
example
{
path: 'user',
component: ViewUserComponent,
resolve: {
user: UserResolve,
},
},
  1. The routerLink will look like this:
example
['user', {userId: row.id}]
  1. On the  ngOnInit hook of the target component, you can read the resolved user like this:
example
this.route.snapshot.data['user']

You can observe this behavior in action in the next two sections, after we update ViewUserComponent and the router to leverage the resolve guard.

..................Content has been hidden....................

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