Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve Guard: Proper way to resolve observable from Routes, if no data found

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.

like image 819
Alex Avatar asked Sep 09 '16 10:09

Alex


People also ask

What is resolve route guard?

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.

What is resolve in angular routes?

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.

What is the use of AuthGuard in angular?

AuthGuard is used to protect the routes from unauthorized access in angular.


1 Answers

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()
}
like image 75
Günter Zöchbauer Avatar answered Nov 15 '22 17:11

Günter Zöchbauer