0

我在 SomeService 中有 NGXS 选择器

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

我在这样的 Angular RouteGuard 中使用它

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();
  }

我收到一个错误“声明类型既不是 'void' 也不是 'any' 的函数必须返回一个值”。我知道原因,因为它没有返回订阅之外的任何内容,但我只想在执行订阅时返回。

4

1 回答 1

1

你应该这样做:

// 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();
}
于 2020-04-21T19:29:11.867 回答