简体   繁体   中英

Angular2 dependency injection abstract class

I was going through the internet to find a solution to a random Angular problem and have encountered the following example:

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 ...
   ...

The ViewportScroller is an abstract class. I am trying to understand the dependency injection in Angular. How can I make an abstract class injectable?

What will be injected is actual class that extends ViewportScroller . Interfacets can serve as injection tokes as well. What will be injected is implementation of given interface provided by some (if any) provider

You can inject an abstract class that has a concrete implementation.

Here is how the ViewportScroller defined in 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)
  });

...

And then, it is implemented by the 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) {}

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM