Angular2 依赖注入摘要 class

Angular2 dependency injection abstract class

我正在通过互联网寻找随机 Angular 问题的解决方案,遇到了以下示例:

export class AppModule {
  constructor(private router: Router, private viewportScroller: ViewportScroller) {
    this.router.events.pipe(
      filter((e: Event): e is Scroll => e instanceof Scroll),
      pairwise()
    ).subscribe((e: Scroll[]) => {
      const previous = e[0];
      const current = e[1];
      if (current.position) {
        this.viewportScroller.scrollToPosition(current.position);
      } else if (current.anchor) {
        this.viewportScroller.scrollToAnchor(current.anchor);
      } else ...
   ...

ViewportScroller 是抽象的 class。我试图了解 Angular 中的依赖注入。如何使抽象 class 可注射?

将注入的是扩展 ViewportScroller 的实际 class。 Interfacets 也可以用作注入令牌。将被注入的是一些(如果有的话)provider

提供的给定接口的实现

您可以注入具有具体实现的抽象 class。

这里是 ViewportScroller 在 Angular source code 中定义的方式:

/**
 * Defines a scroll position manager. Implemented by `BrowserViewportScroller`.
 */
export abstract class ViewportScroller {
  // De-sugared tree-shakable injection
  // See #23917
  /** @nocollapse */
  static ɵprov = ɵɵdefineInjectable({
    token: ViewportScroller,
    providedIn: 'root',
    factory: () => new BrowserViewportScroller(ɵɵinject(DOCUMENT), window)
  });

...

然后,由BrowserViewportScroller:

实现
/**
 * Manages the scroll position for a browser window.
 */
export class BrowserViewportScroller implements ViewportScroller {
  private offset: () => [number, number] = () => [0, 0];

  constructor(private document: Document, private window: Window) {}

...