Q:

Angular2 route resolve multiple actions

Hei, 
I'm having app where we have multiple users and I want to see user details so I need to resolve that user by id before entering the route. All good when I do that if I first land myself to users component which fetches all users. But in case of reload, route tries to resolve user by id and fails because there is no users already (they haven't been fetched yet). I would like to check if users exist, fetch them and then resolve the route with user. Here is the code: 
resolve(route: ActivatedRouteSnapshot): Observable<any>|Promise<any>|any {
  let id = route.params['id'];

  if (!this.usersService.checkIfUsersExist()) {
    return this.usersService.getUsers().subscribe(
           (success) => {
              return this.usersService.getUserById(id); 
           },
           (error) => {
             this.router.navigate([ 'login ']);
           }
    );
 } else {
   return this.usersService.getUserById(id); 
 }
} 

And then in component 
this.route.data.subscribe(
  (res) => { 
    this.user= res['user'];
  }
); 

All I get when I listen to route data is object with user: Subscriber. When I return only this.usersService.getUserById function, user object comes normally. 

A:

Change it to using switchMap:
resolve(route: ActivatedRouteSnapshot): Observable<any>|Promise<any>|any {
  let id = route.params['id'];

  if (!this.usersService.checkIfUsersExist()) {
    return this.usersService.getUsers()
      .switchMap(
           (success) => {
              return this.usersService.getUserById(id); 
           })
      .catch((err) => this.router.navigate([ 'login ']));
 } else {
   return this.usersService.getUserById(id); 
 }
} 

