6

How to return value when using pipe and map, like in this scenario:

return this.service.someEvent().pipe(
  map(x => {
    return this.service.someValue;
  })
)

but the value is never returned since never subscrubed to the event, if i use it like this:

const a = this.service.someEvent().pipe(
  map(x => {
    return this.service.someValue;
  })
)

return a.subscribe();

i get an error (i know this is wrong).

TS2322: Type 'Subscription' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.   Type 'Subscription' is not assignable to type 'Promise<boolean>'.     Property 'then' is missing in type 'Subscription'.

So i need i way to return the value.

UPDATE: the better description (i need to duplicate this code with the latest version of rxjs):

canActivate(next: ActivatedRouteSnapshot,
               state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.service.something().map(x => {
    if (x) {
      return true;
    } else {
      return false;
    }
  })

}

need to do it with map inside pipe (as i understood).

Igor
  • 247
  • 1
  • 7
  • 16
  • 1
    This looks like you're trying to call `return a.subscribe();` in a method whose typings say it should return `Observable`. Function `subscribe()` returns `Subscription` instance – martin May 16 '18 at 15:38

1 Answers1

3

You can simply return the observable itself from the "canActivate" guard :-

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  return this.service.something().pipe(map(x => {
    if (x) {
      return true;
    } else {
      return false;
    }
  }));
}

Routing will proceed only after the returned observable is complete and its emitted value is true. So you don't actually have to worry about subscribing to that observable angular router will handle it of its own.

Yatharth Varshney
  • 1,973
  • 20
  • 22
  • is it really when the observable is complete or is it when the observable receives its next value? I think it's the latter? – bersling Jan 19 '22 at 21:04