角度-找出派生类是否实现了抽象类(router.component)

时间:2020-07-27 19:07:52

标签: angular typescript abstract-class

我正在尝试使用router.component来设置页面标题。因此,我创建了一个抽象类,必须提供标题:

export abstract class ComponentWithTitleBase {
  abstract get title(): Observable<string>;
}

,然后实现它的组件如下所示:

export class AboutComponent extends ComponentWithTitleBase implements OnInit {
  get title(): Observable<string> {
    return of("About the demo");
  }

  ngOnInit(): void {}
}

现在我只需要在路由器事件中使用它。我订阅并查看router.component是否为ComponentWithTitleBase,所以:

    this.router.events
      .pipe(
        // identify navigation end
        filter((event) => event instanceof NavigationEnd),
        // now query the activated route
        map(() => this.rootRoute(this.route)),
        filter((route) => !!route.component),
        tap((route: ActivatedRoute) =>
          console.log(route.component instanceof ComponentWithTitleBase)
        ),
...

但是我做的输出是false。我有什么办法可以找出某个类是否实现了另一个 抽象 类?

1 个答案:

答案 0 :(得分:0)

instanceof 不适用于抽象类,

route.component instanceof ComponentWithTitleBase替换为 ComponentWithTitleBase.isPrototypeOf(route.component)