Angular 11 与 rxjs 问题 - TS2769:没有重载匹配此调用

Angular 11 with rxjs issue - TS2769: No overload matches this call

我想订阅 Angular 11 中的 NavigationEnd 事件,同时使用来自 rxjs 的过滤器。

subscribe((event: NavigationEnd) ...的部分导致以下问题

当前解决方案:

TS2769: No overload matches this call.   Overload 1 of 5, '(observer?: NextObserver | ErrorObserver | CompletionObserver | undefined): Subscription', gave the following error.     Argument of type '(event: NavigationEnd) => void' is not assignable to parameter of type 'NextObserver | ErrorObserver | CompletionObserver | undefined'.       Property 'complete' is missing in type '(event: NavigationEnd) => void' but required in type 'CompletionObserver'.   Overload 2 of 5, '(next?: ((value: Event) => void) | undefined, error?: ((error: any) => void) | undefined, complete?: (() => void) | undefined): Subscription', gave the following error.     Argument of type '(event: NavigationEnd) => void' is not assignable to parameter of type '(value: Event) => void'.       Types of parameters 'event' and 'value' are incompatible.         Type 'Event' is not assignable to type 'NavigationEnd'.           Property 'urlAfterRedirects' is missing in type 'RouterEvent' but required in type 'NavigationEnd'.

请参阅下面提到的代码片段的构造函数代码:

export class NavigationService implements OnDestroy {
  private readonly routeChange: Subscription | undefined;
  private previousUrl: string | undefined;
  private ignoredRoutes = ['/signup', '/login', '/reset'];

  constructor(private router: Router) {
    this.routeChange = router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => {
        if (!this.ignoredRoutes.includes(event.url)) {
          this.previousUrl = event.url;
        }
      });
  }

  ngOnDestroy(): void {
    if (this.routeChange) {
      this.routeChange.unsubscribe();
    }
  }

  public routeToPreviousContent(): void {
    //route home if undefined
    const targetUrl = this.previousUrl ? this.previousUrl : '';
    this.router.navigate([targetUrl]).then();
  }
}

TS2769 在这种情况下是否有效?我假设带有 event instanceof NavigationEnd 的 rxjs 过滤器管道根本无法识别?!

传递给过滤器的函数不是类型保护,但您可以这样指示类型:

constructor(private router: Router) {
  this.routeChange = router.events
    .pipe(
      filter((event): event is NavigationEnd => event instanceof NavigationEnd)
    )
    .subscribe(event => {
      // "event" here is now of type "NavigationEnd"
    });
}