angularngxsangular-route-guards

canActivate and NGXS selector


I have NGXS selector in SomeService

@Select(state => state.sample)
public sample$: Observable<Sample>;

I am using it inside an Angular RouteGuard like this

getSample(): boolean {
    this.someService.sample$.subscribe({
      next: (sample: Sample) => {
        if (isValid(sample)) {
          return true;
        } else {
          return false;
        }
      },
      error: () => {
        return false;
      }
    });
  }

  canActivate(): boolean {
    return this.getSample();
  }

I am getting an error 'A function whose declared type is neither 'void' nor 'any' must return a value'. I know the cause because it did not return anything outside subscribe, but I want to return only upon executing subscribe.


Solution

  • You should do something like this:

    // You cannot return the value the way you were trying to do. 
    // The following snippet shows the right way to do it.
    // Notice we're returning an observable instead of a boolean.
    // And we are making sure that the observable completes after
    // the first emission, by using the `take(1)` operator
    getSample(): Observable<boolean> {
      return this.someService.sample$.pipe(
        // Convert the sample to true or false according to isValid
        map((sample: Sample) => isValid(sample)),
        // The observable must complete for canActivate get into action
        take(1)
      }
    }
    
    // Can activate can return an Observable<boolean> as long
    // as it completes.
    canActivate(): Observable<boolean> {
      return this.getSample();
    }