0

I have a question on resolving some data for my Angular 2 route.

I created a resolver service that should return boolean value based on some condition.

However, the problem I am facing with is that in resolve method I need to call this.hotelService.getAll().subscribe(hotels => this.hotels = hotels) that executes last (after return statement).

This is the code:

  resolve(routeSnapshot: ActivatedRouteSnapshot) {
    this.hotelService.getAll(this.authenticationService.getUser()
      .subscribe((hotels) => {
        this.hotels = hotels;
      });
    return this.hotelService.hasManyCorporations(this.hotels); // => clear true/false value returned
  }

As you may notice, in the return statement I am trying to pass this.hotels value to hasManyCorporations method but undefined is present, because this.hotels = hotels block of code is not yet executed at the time of executing return statement.

How to deal with this situation in which I have a delay of 2-3 seconds? This is my whole resolver service:

@Injectable()
export class HasManyCorporationResolveService implements Resolve<any> {

  private hotels: Hotel[];

  constructor(
    private corporationService: CorporationService,
    private authenticationService: AuthenticationService,
    private hotelService: HotelService
  ) { }

  resolve(routeSnapshot: ActivatedRouteSnapshot) {

    this.hotelService.getAll(this.authenticationService.getUser().id)
      .subscribe((hotels) => {
        this.hotels = hotels;
      });
    return this.hotelService.hasManyCorporations(this.hotels); // clear true/false value returned
  }

}
mixi
  • 47
  • 9
  • What about `this.hotelService.getAll(.....).do(x => this.hotels = x).map(x => this.hotelService.hasManyCorporations(x));` If `this.hotelService.hasManyCorporations` returns an Observable use `switchMap` instead of `map` If this works let me know and I will add it as an answer :) – Peter Morris Aug 12 '17 at 19:47
  • @PeterMorris what would that do differently? getAll method returns an array of Observables, so I need to somehow subscribe to get clean values. – mixi Aug 12 '17 at 21:46
  • You need to include more source code in your question. Add the getAll source. – Peter Morris Aug 12 '17 at 22:34
  • You misunderstood the purpose of observables. This is a special case of http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call . The point here is that you can't do this and you shouldn't - the whole idea of resolvers is that they are primarily used for async code and can return promises or observables. – Estus Flask Aug 12 '17 at 23:03
  • @estus so the solution to my problem is what exactly? – mixi Aug 13 '17 at 17:07
  • Return an observable instead of trying to return a boolean (it's not possible). – Estus Flask Aug 13 '17 at 18:59

0 Answers0