puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Resolve in Angular Routing #16

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

Resolve is Interface that classes can implement to be a data provider. A data provider class can be used with the router to resolve data during navigation. The interface defines a resolve() method that will be invoked when the navigation starts. The router will then wait for the data to be resolved before the route is finally activated. Getting data before navigating to the new route.

Resolver is a service which has to be [provided] in root module.

interface Resolve<T> {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T
}

Why to use Resolve

  1. To ensure data obtained => routing works, prevent empty component display due to data delayed, to enhance better UI experience
  2. To routing interception, e.g. some website, if the user is not logged in, then when opening some pages, it will warn: not logged in, then force user to jump back to the last page. But if it is used with resolve, then it could pre-judge the login status before openning the new page.

Difference between a Resolver and normal process

1. General Routing Flow.

2. Routing Flow with Resolver

Steps 2,3 and 4 are done with a code called Resolver.

How does a Resolve work

1. Creating a Resolver.

1st requirement to implement the Angular router’s Resolve interface is that the export class has a resolve method. Whatever is returned from that method will be the resolved data.

@Injectable()
export class SampleClassResolve implements Resolve<Observable<string>> {
  constructor() {}

  resolve() {
    return Observable.of('Hello Sample!').delay(2000);
  }
}

2. Defining a Resolver in Route

then should be the setting up inside routing of app.module.ts .This resolve key holds another object where you will define a key and assign your resolver service as a value to it.

const routes: Routes = [
  {
    path:'sample',
    component:'SampleNavComponent',
    resolve: { message: SampleClassResolver }
  }
]

//message is the key which i have defined and it holds SampleClassResolve service

@NgModules
providers: [
    SampleClassResolver
  ]

Logic

Therefore the browser will follow this logic, parent.component => SampleClassResolver =>SampleNavComponent Therefore the browser will obtain data before reach SampleNavComponent

3.Using Resolver

3rd step is to access the resolve inside a component.Then we can access the resolved data using the data property of ActivatedRoute’s snapshot object:

data: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.data = this.route.snapshot.data;
  }

then inside the template, the message key will be used

<p>The message: {{data.message}}</p>

[Source:]

Angular Router: Route Resolvers Angular Resolve Understanding Resolvers in Angular