{ "id": "guide/dependency-injection-in-action", "title": "Dependency injection in action", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Dependency injection in actionlink

\n

This guide explores many of the features of dependency injection (DI) in Angular.

\n
\n

See the for a working example containing the code snippets in this guide.

\n
\n\n

Multiple service instances (sandboxing)link

\n

Sometimes you want multiple instances of a service at the same level of the component hierarchy.

\n

A good example is a service that holds state for its companion component instance.\nYou need a separate instance of the service for each component.\nEach service has its own work-state, isolated from the service-and-state of a different component.\nThis is called sandboxing because each service and component instance has its own sandbox to play in.

\n\n

In this example, HeroBiosComponent presents three instances of HeroBioComponent.

\n\n@Component({\n selector: 'app-hero-bios',\n template: `\n <app-hero-bio [heroId]=\"1\"></app-hero-bio>\n <app-hero-bio [heroId]=\"2\"></app-hero-bio>\n <app-hero-bio [heroId]=\"3\"></app-hero-bio>`,\n providers: [HeroService]\n})\nexport class HeroBiosComponent {\n}\n\n\n

Each HeroBioComponent can edit a single hero's biography.\nHeroBioComponent relies on HeroCacheService to fetch, cache, and perform other persistence operations on that hero.

\n\n@Injectable()\nexport class HeroCacheService {\n hero: Hero;\n constructor(private heroService: HeroService) {}\n\n fetchCachedHero(id: number) {\n if (!this.hero) {\n this.hero = this.heroService.getHeroById(id);\n }\n return this.hero;\n }\n}\n\n\n

Three instances of HeroBioComponent can't share the same instance of HeroCacheService,\nas they'd be competing with each other to determine which hero to cache.

\n

Instead, each HeroBioComponent gets its own HeroCacheService instance\nby listing HeroCacheService in its metadata providers array.

\n\n@Component({\n selector: 'app-hero-bio',\n template: `\n <h4>{{hero.name}}</h4>\n <ng-content></ng-content>\n <textarea cols=\"25\" [(ngModel)]=\"hero.description\"></textarea>`,\n providers: [HeroCacheService]\n})\n\nexport class HeroBioComponent implements OnInit {\n @Input() heroId: number;\n\n constructor(private heroCache: HeroCacheService) { }\n\n ngOnInit() { this.heroCache.fetchCachedHero(this.heroId); }\n\n get hero() { return this.heroCache.hero; }\n}\n\n\n

The parent HeroBiosComponent binds a value to heroId.\nngOnInit passes that ID to the service, which fetches and caches the hero.\nThe getter for the hero property pulls the cached hero from the service.\nThe template displays this data-bound property.

\n

Find this example in live code\nand confirm that the three HeroBioComponent instances have their own cached hero data.

\n
\n \"Bios\"\n
\n\n

Qualify dependency lookup with parameter decoratorslink

\n

When a class requires a dependency, that dependency is added to the constructor as a parameter.\nWhen Angular needs to instantiate the class, it calls upon the DI framework to supply the dependency.\nBy default, the DI framework searches for a provider in the injector hierarchy,\nstarting at the component's local injector of the component, and if necessary bubbling up\nthrough the injector tree until it reaches the root injector.

\n\n

There are a number of options for modifying the default search behavior, using parameter decorators\non the service-valued parameters of a class constructor.

\n\n

Make a dependency @Optional and limit search with @Hostlink

\n

Dependencies can be registered at any level in the component hierarchy.\nWhen a component requests a dependency, Angular starts with that component's injector\nand walks up the injector tree until it finds the first suitable provider.\nAngular throws an error if it can't find the dependency during that walk.

\n

In some cases, you need to limit the search or accommodate a missing dependency.\nYou can modify Angular's search behavior with the @Host and @Optional qualifying\ndecorators on a service-valued parameter of the component's constructor.

\n\n

These decorators can be used individually or together, as shown in the example.\nThis HeroBiosAndContactsComponent is a revision of HeroBiosComponent which you looked at above.

\n\n@Component({\n selector: 'app-hero-bios-and-contacts',\n template: `\n <app-hero-bio [heroId]=\"1\"> <app-hero-contact></app-hero-contact> </app-hero-bio>\n <app-hero-bio [heroId]=\"2\"> <app-hero-contact></app-hero-contact> </app-hero-bio>\n <app-hero-bio [heroId]=\"3\"> <app-hero-contact></app-hero-contact> </app-hero-bio>`,\n providers: [HeroService]\n})\nexport class HeroBiosAndContactsComponent {\n constructor(logger: LoggerService) {\n logger.logInfo('Creating HeroBiosAndContactsComponent');\n }\n}\n\n\n

Focus on the template:

\n\ntemplate: `\n <app-hero-bio [heroId]=\"1\"> <app-hero-contact></app-hero-contact> </app-hero-bio>\n <app-hero-bio [heroId]=\"2\"> <app-hero-contact></app-hero-contact> </app-hero-bio>\n <app-hero-bio [heroId]=\"3\"> <app-hero-contact></app-hero-contact> </app-hero-bio>`,\n\n\n

Now there's a new <hero-contact> element between the <hero-bio> tags.\nAngular projects, or transcludes, the corresponding HeroContactComponent into the HeroBioComponent view,\nplacing it in the <ng-content> slot of the HeroBioComponent template.

\n\ntemplate: `\n <h4>{{hero.name}}</h4>\n <ng-content></ng-content>\n <textarea cols=\"25\" [(ngModel)]=\"hero.description\"></textarea>`,\n\n\n

The result is shown below, with the hero's telephone number from HeroContactComponent projected above the hero description.

\n
\n \"bio\n
\n

Here's HeroContactComponent, which demonstrates the qualifying decorators.

\n\n@Component({\n selector: 'app-hero-contact',\n template: `\n <div>Phone #: {{phoneNumber}}\n <span *ngIf=\"hasLogger\">!!!</span></div>`\n})\nexport class HeroContactComponent {\n\n hasLogger = false;\n\n constructor(\n @Host() // limit to the host component's instance of the HeroCacheService\n private heroCache: HeroCacheService,\n\n @Host() // limit search for logger; hides the application-wide logger\n @Optional() // ok if the logger doesn't exist\n private loggerService?: LoggerService\n ) {\n if (loggerService) {\n this.hasLogger = true;\n loggerService.logInfo('HeroContactComponent can log!');\n }\n }\n\n get phoneNumber() { return this.heroCache.hero.phone; }\n\n}\n\n\n

Focus on the constructor parameters.

\n\n@Host() // limit to the host component's instance of the HeroCacheService\nprivate heroCache: HeroCacheService,\n\n@Host() // limit search for logger; hides the application-wide logger\n@Optional() // ok if the logger doesn't exist\nprivate loggerService?: LoggerService\n\n\n

The @Host() function decorating the heroCache constructor property ensures that\nyou get a reference to the cache service from the parent HeroBioComponent.\nAngular throws an error if the parent lacks that service, even if a component higher\nin the component tree includes it.

\n

A second @Host() function decorates the loggerService constructor property.\nThe only LoggerService instance in the app is provided at the AppComponent level.\nThe host HeroBioComponent doesn't have its own LoggerService provider.

\n

Angular throws an error if you haven't also decorated the property with @Optional().\nWhen the property is marked as optional, Angular sets loggerService to null and the rest of the component adapts.

\n

Here's HeroBiosAndContactsComponent in action.

\n
\n \"Bios\n
\n

If you comment out the @Host() decorator, Angular walks up the injector ancestor tree\nuntil it finds the logger at the AppComponent level.\nThe logger logic kicks in and the hero display updates\nwith the \"!!!\" marker to indicate that the logger was found.

\n
\n \"Without\n
\n

If you restore the @Host() decorator and comment out @Optional,\nthe app throws an exception when it cannot find the required logger at the host component level.

\n

EXCEPTION: No provider for LoggerService! (HeroContactComponent -> LoggerService)

\n

Supply a custom provider with @Injectlink

\n

Using a custom provider allows you to provide a concrete implementation for implicit dependencies, such as built-in browser APIs. The following example uses an InjectionToken to provide the localStorage browser API as a dependency in the BrowserStorageService.

\n\nimport { Inject, Injectable, InjectionToken } from '@angular/core';\n\nexport const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {\n providedIn: 'root',\n factory: () => localStorage\n});\n\n@Injectable({\n providedIn: 'root'\n})\nexport class BrowserStorageService {\n constructor(@Inject(BROWSER_STORAGE) public storage: Storage) {}\n\n get(key: string) {\n return this.storage.getItem(key);\n }\n\n set(key: string, value: string) {\n this.storage.setItem(key, value);\n }\n\n remove(key: string) {\n this.storage.removeItem(key);\n }\n\n clear() {\n this.storage.clear();\n }\n}\n\n\n\n

The factory function returns the localStorage property that is attached to the browser window object. The Inject decorator is a constructor parameter used to specify a custom provider of a dependency. This custom provider can now be overridden during testing with a mock API of localStorage instead of interacting with real browser APIs.

\n\n

Modify the provider search with @Self and @SkipSelflink

\n

Providers can also be scoped by injector through constructor parameter decorators. The following example overrides the BROWSER_STORAGE token in the Component class providers with the sessionStorage browser API. The same BrowserStorageService is injected twice in the constructor, decorated with @Self and @SkipSelf to define which injector handles the provider dependency.

\n\nimport { Component, OnInit, Self, SkipSelf } from '@angular/core';\nimport { BROWSER_STORAGE, BrowserStorageService } from './storage.service';\n\n@Component({\n selector: 'app-storage',\n template: `\n Open the inspector to see the local/session storage keys:\n\n <h3>Session Storage</h3>\n <button (click)=\"setSession()\">Set Session Storage</button>\n\n <h3>Local Storage</h3>\n <button (click)=\"setLocal()\">Set Local Storage</button>\n `,\n providers: [\n BrowserStorageService,\n { provide: BROWSER_STORAGE, useFactory: () => sessionStorage }\n ]\n})\nexport class StorageComponent implements OnInit {\n\n constructor(\n @Self() private sessionStorageService: BrowserStorageService,\n @SkipSelf() private localStorageService: BrowserStorageService,\n ) { }\n\n ngOnInit() {\n }\n\n setSession() {\n this.sessionStorageService.set('hero', 'Dr Nice - Session');\n }\n\n setLocal() {\n this.localStorageService.set('hero', 'Dr Nice - Local');\n }\n}\n\n\n\n

Using the @Self decorator, the injector only looks at the component's injector for its providers. The @SkipSelf decorator allows you to skip the local injector and look up in the hierarchy to find a provider that satisfies this dependency. The sessionStorageService instance interacts with the BrowserStorageService using the sessionStorage browser API, while the localStorageService skips the local injector and uses the root BrowserStorageService that uses the localStorage browser API.

\n\n

Inject the component's DOM elementlink

\n

Although developers strive to avoid it, many visual effects and third-party tools, such as jQuery,\nrequire DOM access.\nAs a result, you might need to access a component's DOM element.

\n

To illustrate, here's a minimal version of HighlightDirective from\nthe Attribute Directives page.

\n\nimport { Directive, ElementRef, HostListener, Input } from '@angular/core';\n\n@Directive({\n selector: '[appHighlight]'\n})\nexport class HighlightDirective {\n\n @Input('appHighlight') highlightColor: string;\n\n private el: HTMLElement;\n\n constructor(el: ElementRef) {\n this.el = el.nativeElement;\n }\n\n @HostListener('mouseenter') onMouseEnter() {\n this.highlight(this.highlightColor || 'cyan');\n }\n\n @HostListener('mouseleave') onMouseLeave() {\n this.highlight(null);\n }\n\n private highlight(color: string) {\n this.el.style.backgroundColor = color;\n }\n}\n\n\n\n

The directive sets the background to a highlight color when the user mouses over the\nDOM element to which the directive is applied.

\n

Angular sets the constructor's el parameter to the injected ElementRef.\n(An ElementRef is a wrapper around a DOM element,\nwhose nativeElement property exposes the DOM element for the directive to manipulate.)

\n

The sample code applies the directive's myHighlight attribute to two <div> tags,\nfirst without a value (yielding the default color) and then with an assigned color value.

\n\n<div id=\"highlight\" class=\"di-component\" appHighlight>\n <h3>Hero Bios and Contacts</h3>\n <div appHighlight=\"yellow\">\n <app-hero-bios-and-contacts></app-hero-bios-and-contacts>\n </div>\n</div>\n\n\n

The following image shows the effect of mousing over the <hero-bios-and-contacts> tag.

\n
\n \"Highlighted\n
\n\n

Defining providerslink

\n

A dependency can't always be created by the default method of instantiating a class.\nYou learned about some other methods in Dependency Providers.\nThe following HeroOfTheMonthComponent example demonstrates many of the alternatives and why you need them.\nIt's visually simple: a few properties and the logs produced by a logger.

\n
\n \"Hero\n
\n

The code behind it customizes how and where the DI framework provides dependencies.\nThe use cases illustrate different ways to use the provide object literal to associate a definition object with a DI token.

\n\nimport { Component, Inject } from '@angular/core';\n\nimport { DateLoggerService } from './date-logger.service';\nimport { Hero } from './hero';\nimport { HeroService } from './hero.service';\nimport { LoggerService } from './logger.service';\nimport { MinimalLogger } from './minimal-logger.service';\nimport { RUNNERS_UP,\n runnersUpFactory } from './runners-up';\n\n@Component({\n selector: 'app-hero-of-the-month',\n templateUrl: './hero-of-the-month.component.html',\n providers: [\n { provide: Hero, useValue: someHero },\n { provide: TITLE, useValue: 'Hero of the Month' },\n { provide: HeroService, useClass: HeroService },\n { provide: LoggerService, useClass: DateLoggerService },\n { provide: MinimalLogger, useExisting: LoggerService },\n { provide: RUNNERS_UP, useFactory: runnersUpFactory(2), deps: [Hero, HeroService] }\n ]\n})\nexport class HeroOfTheMonthComponent {\n logs: string[] = [];\n\n constructor(\n logger: MinimalLogger,\n public heroOfTheMonth: Hero,\n @Inject(RUNNERS_UP) public runnersUp: string,\n @Inject(TITLE) public title: string)\n {\n this.logs = logger.logs;\n logger.logInfo('starting up');\n }\n}\n\n\n

The providers array shows how you might use the different provider-definition keys;\nuseValue, useClass, useExisting, or useFactory.

\n\n

Value providers: useValuelink

\n

The useValue key lets you associate a fixed value with a DI token.\nUse this technique to provide runtime configuration constants such as website base addresses and feature flags.\nYou can also use a value provider in a unit test to provide mock data in place of a production data service.

\n

The HeroOfTheMonthComponent example has two value providers.

\n\n{ provide: Hero, useValue: someHero },\n{ provide: TITLE, useValue: 'Hero of the Month' },\n\n\n\n

You can use an injection token for any kind of provider but it's particularly\nhelpful when the dependency is a simple value like a string, a number, or a function.

\n

The value of a value provider must be defined before you specify it here.\nThe title string literal is immediately available.\nThe someHero variable in this example was set earlier in the file as shown below.\nYou can't use a variable whose value will be defined later.

\n\nconst someHero = new Hero(42, 'Magma', 'Had a great month!', '555-555-5555');\n\n\n

Other types of providers can create their values lazily; that is, when they're needed for injection.

\n\n

Class providers: useClasslink

\n

The useClass provider key lets you create and return a new instance of the specified class.

\n

You can use this type of provider to substitute an alternative implementation\nfor a common or default class.\nThe alternative implementation could, for example, implement a different strategy,\nextend the default class, or emulate the behavior of the real class in a test case.

\n

The following code shows two examples in HeroOfTheMonthComponent.

\n\n{ provide: HeroService, useClass: HeroService },\n{ provide: LoggerService, useClass: DateLoggerService },\n\n\n

The first provider is the de-sugared, expanded form of the most typical case in which the\nclass to be created (HeroService) is also the provider's dependency injection token.\nThe short form is generally preferred; this long form makes the details explicit.

\n

The second provider substitutes DateLoggerService for LoggerService.\nLoggerService is already registered at the AppComponent level.\nWhen this child component requests LoggerService, it receives a DateLoggerService instance instead.

\n
\n

This component and its tree of child components receive DateLoggerService instance.\nComponents outside the tree continue to receive the original LoggerService instance.

\n
\n

DateLoggerService inherits from LoggerService; it appends the current date/time to each message:

\n\n@Injectable({\n providedIn: 'root'\n})\nexport class DateLoggerService extends LoggerService\n{\n logInfo(msg: any) { super.logInfo(stamp(msg)); }\n logDebug(msg: any) { super.logInfo(stamp(msg)); }\n logError(msg: any) { super.logError(stamp(msg)); }\n}\n\nfunction stamp(msg: any) { return msg + ' at ' + new Date(); }\n\n\n\n

Alias providers: useExistinglink

\n

The useExisting provider key lets you map one token to another.\nIn effect, the first token is an alias for the service associated with the second token,\ncreating two ways to access the same service object.

\n\n{ provide: MinimalLogger, useExisting: LoggerService },\n\n\n

You can use this technique to narrow an API through an aliasing interface.\nThe following example shows an alias introduced for that purpose.

\n

Imagine that LoggerService had a large API, much larger than the actual three methods and a property.\nYou might want to shrink that API surface to just the members you actually need.\nIn this example, the MinimalLogger class-interface reduces the API to two members:

\n\n// Class used as a \"narrowing\" interface that exposes a minimal logger\n// Other members of the actual implementation are invisible\nexport abstract class MinimalLogger {\n logs: string[];\n logInfo: (msg: string) => void;\n}\n\n\n

The following example puts MinimalLogger to use in a simplified version of HeroOfTheMonthComponent.

\n\n@Component({\n selector: 'app-hero-of-the-month',\n templateUrl: './hero-of-the-month.component.html',\n // TODO: move this aliasing, `useExisting` provider to the AppModule\n providers: [{ provide: MinimalLogger, useExisting: LoggerService }]\n})\nexport class HeroOfTheMonthComponent {\n logs: string[] = [];\n constructor(logger: MinimalLogger) {\n logger.logInfo('starting up');\n }\n}\n\n\n

The HeroOfTheMonthComponent constructor's logger parameter is typed as MinimalLogger, so only the logs and logInfo members are visible in a TypeScript-aware editor.

\n
\n \"MinimalLogger\n
\n

Behind the scenes, Angular sets the logger parameter to the full service registered under the LoggingService token, which happens to be the DateLoggerService instance that was provided above.

\n
\n

This is illustrated in the following image, which displays the logging date.

\n
\n \"DateLoggerService\n
\n
\n\n

Factory providers: useFactorylink

\n

The useFactory provider key lets you create a dependency object by calling a factory function,\nas in the following example.

\n\n{ provide: RUNNERS_UP, useFactory: runnersUpFactory(2), deps: [Hero, HeroService] }\n\n\n

The injector provides the dependency value by invoking a factory function,\nthat you provide as the value of the useFactory key.\nNotice that this form of provider has a third key, deps, which specifies\ndependencies for the useFactory function.

\n

Use this technique to create a dependency object with a factory function\nwhose inputs are a combination of injected services and local state.

\n

The dependency object (returned by the factory function) is typically a class instance,\nbut can be other things as well.\nIn this example, the dependency object is a string of the names of the runners up\nto the \"Hero of the Month\" contest.

\n

In the example, the local state is the number 2, the number of runners up that the component should show.\nThe state value is passed as an argument to runnersUpFactory().\nThe runnersUpFactory() returns the provider factory function, which can use both\nthe passed-in state value and the injected services Hero and HeroService.

\n\nexport function runnersUpFactory(take: number) {\n return (winner: Hero, heroService: HeroService): string => {\n /* ... */\n };\n}\n\n\n

The provider factory function (returned by runnersUpFactory()) returns the actual dependency object,\nthe string of names.

\n\n
\n

The function retrieves candidate heroes from the HeroService,\ntakes 2 of them to be the runners-up, and returns their concatenated names.\nLook at the \nfor the full source code.

\n
\n\n

Provider token alternatives: class interface and 'InjectionToken'link

\n

Angular dependency injection is easiest when the provider token is a class\nthat is also the type of the returned dependency object, or service.

\n

However, a token doesn't have to be a class and even when it is a class,\nit doesn't have to be the same type as the returned object.\nThat's the subject of the next section.\n

\n

Class interfacelink

\n

The previous Hero of the Month example used the MinimalLogger class\nas the token for a provider of LoggerService.

\n\n{ provide: MinimalLogger, useExisting: LoggerService },\n\n\n

MinimalLogger is an abstract class.

\n\n// Class used as a \"narrowing\" interface that exposes a minimal logger\n// Other members of the actual implementation are invisible\nexport abstract class MinimalLogger {\n logs: string[];\n logInfo: (msg: string) => void;\n}\n\n\n

An abstract class is usually a base class that you can extend.\nIn this app, however there is no class that inherits from MinimalLogger.\nThe LoggerService and the DateLoggerService could have inherited from MinimalLogger,\nor they could have implemented it instead, in the manner of an interface.\nBut they did neither.\nMinimalLogger is used only as a dependency injection token.

\n

When you use a class this way, it's called a class interface.

\n

As mentioned in DI Providers,\nan interface is not a valid DI token because it is a TypeScript artifact that doesn't exist at run time.\nUse this abstract class interface to get the strong typing of an interface,\nand also use it as a provider token in the way you would a normal class.

\n

A class interface should define only the members that its consumers are allowed to call.\nSuch a narrowing interface helps decouple the concrete class from its consumers.

\n
\n

Using a class as an interface gives you the characteristics of an interface in a real JavaScript object.\nTo minimize memory cost, however, the class should have no implementation.\nThe MinimalLogger transpiles to this unoptimized, pre-minified JavaScript for a constructor function.

\n\nvar MinimalLogger = (function () {\n function MinimalLogger() {}\n return MinimalLogger;\n}());\nexports(\"MinimalLogger\", MinimalLogger);\n\n\n

Notice that it doesn't have any members. It never grows no matter how many members you add to the class,\nas long as those members are typed but not implemented.

\n

Look again at the TypeScript MinimalLogger class to confirm that it has no implementation.

\n
\n\n

'InjectionToken' objectslink

\n

Dependency objects can be simple values like dates, numbers and strings, or\nshapeless objects like arrays and functions.

\n

Such objects don't have application interfaces and therefore aren't well represented by a class.\nThey're better represented by a token that is both unique and symbolic,\na JavaScript object that has a friendly name but won't conflict with\nanother token that happens to have the same name.

\n

InjectionToken has these characteristics.\nYou encountered them twice in the Hero of the Month example,\nin the title value provider and in the runnersUp factory provider.

\n\n{ provide: TITLE, useValue: 'Hero of the Month' },\n{ provide: RUNNERS_UP, useFactory: runnersUpFactory(2), deps: [Hero, HeroService] }\n\n\n

You created the TITLE token like this:

\n\nimport { InjectionToken } from '@angular/core';\n\nexport const TITLE = new InjectionToken<string>('title');\n\n\n

The type parameter, while optional, conveys the dependency's type to developers and tooling.\nThe token description is another developer aid.

\n\n

Inject into a derived classlink

\n

Take care when writing a component that inherits from another component.\nIf the base component has injected dependencies,\nyou must re-provide and re-inject them in the derived class\nand then pass them down to the base class through the constructor.

\n

In this contrived example, SortedHeroesComponent inherits from HeroesBaseComponent\nto display a sorted list of heroes.

\n
\n \"Sorted\n
\n

The HeroesBaseComponent can stand on its own.\nIt demands its own instance of HeroService to get heroes\nand displays them in the order they arrive from the database.

\n\n@Component({\n selector: 'app-unsorted-heroes',\n template: `<div *ngFor=\"let hero of heroes\">{{hero.name}}</div>`,\n providers: [HeroService]\n})\nexport class HeroesBaseComponent implements OnInit {\n constructor(private heroService: HeroService) { }\n\n heroes: Array<Hero>;\n\n ngOnInit() {\n this.heroes = this.heroService.getAllHeroes();\n this.afterGetHeroes();\n }\n\n // Post-process heroes in derived class override.\n protected afterGetHeroes() {}\n\n}\n\n\n
\n

Keep constructors simplelink

\n

Constructors should do little more than initialize variables.\nThis rule makes the component safe to construct under test without fear that it will do something dramatic like talk to the server.\nThat's why you call the HeroService from within the ngOnInit rather than the constructor.

\n
\n

Users want to see the heroes in alphabetical order.\nRather than modify the original component, sub-class it and create a\nSortedHeroesComponent that sorts the heroes before presenting them.\nThe SortedHeroesComponent lets the base class fetch the heroes.

\n

Unfortunately, Angular cannot inject the HeroService directly into the base class.\nYou must provide the HeroService again for this component,\nthen pass it down to the base class inside the constructor.

\n\n@Component({\n selector: 'app-sorted-heroes',\n template: `<div *ngFor=\"let hero of heroes\">{{hero.name}}</div>`,\n providers: [HeroService]\n})\nexport class SortedHeroesComponent extends HeroesBaseComponent {\n constructor(heroService: HeroService) {\n super(heroService);\n }\n\n protected afterGetHeroes() {\n this.heroes = this.heroes.sort((h1, h2) => {\n return h1.name < h2.name ? -1 :\n (h1.name > h2.name ? 1 : 0);\n });\n }\n}\n\n\n

Now take note of the afterGetHeroes() method.\nYour first instinct might have been to create an ngOnInit method in SortedHeroesComponent and do the sorting there.\nBut Angular calls the derived class's ngOnInit before calling the base class's ngOnInit\nso you'd be sorting the heroes array before they arrived. That produces a nasty error.

\n

Overriding the base class's afterGetHeroes() method solves the problem.

\n

These complications argue for avoiding component inheritance.

\n\n

Break circularities with a forward class reference (forwardRef)link

\n

The order of class declaration matters in TypeScript.\nYou can't refer directly to a class until it's been defined.

\n

This isn't usually a problem, especially if you adhere to the recommended one class per file rule.\nBut sometimes circular references are unavoidable.\nYou're in a bind when class 'A' refers to class 'B' and 'B' refers to 'A'.\nOne of them has to be defined first.

\n

The Angular forwardRef() function creates an indirect reference that Angular can resolve later.

\n

The Parent Finder sample is full of circular class references that are impossible to break.

\n

You face this dilemma when a class makes a reference to itself\nas does AlexComponent in its providers array.\nThe providers array is a property of the @Component() decorator function which must\nappear above the class definition.

\n

Break the circularity with forwardRef.

\n\nproviders: [{ provide: Parent, useExisting: forwardRef(() => AlexComponent) }],\n\n\n\n \n
\n\n\n" }