resolve method in the example on the angular.io returns a promise or navigates the application to the specific route if no data was found.
resolve(route: ActivatedRouteSnapshot): Promise<any> {
let id = +route.params['id'];
return this.cs.getCrisis(id).then(crisis => {
if (crisis) {
return crisis;
} else { // id not found
this.router.navigate(['/crisis-center']);
return false;
}
});
}
suppose, that getCrisis function returning an observable:
resolve(route: ActivatedRouteSnapshot): Observable<any> {
let id = +route.params['id'];
return this.cs.getCrisis(id).take(1)
}
in case of observable. How do i know, that nothing is returned, as i am dealing with stream? what would be the best pattern to handle this case inside the resolve function?
I know, that i could user router.navigate method from the component, but would like to use the router resolve guard properly.
Resolve guard is used in the scenario when we want to ensure whether there is data available or not before navigating to any route. If there is no data then it has no meaning to navigate there. It means we have to resolve data before navigating to that route. Here comes the role of Angular Resolve guard.
So what is Angular Resolver? Angular Route Resolver is used for pre-fetching some of the data when the user is navigating from one route to another. It can be defined as a smooth approach for enhancing user experience by loading data before the user navigates to a particular component.
AuthGuard is used to protect the routes from unauthorized access in angular.
You might need to add .first()
(needs to be imported) because currently the router waits for the observable to complete and that might not happen depending on what getCrisis()
is doing:
resolve(route: ActivatedRouteSnapshot): Observable<any> {
let id = +route.params['id'];
return this.cs.getCrisis(id)
.map(data => {
if(data) {
return crisis;
} else {
this.router.navigate(['/crisis-center']);
return false;
}
})
.first()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With