The Hierarchy of Injectors
Explore how Angular employs a hierarchical system to use the different types of injectors.
Injectors in Angular
We have seen three types of decorators:
These injectors are used to tell Angular something about the class.
Injectors hierarchy
With these three different injectors knowing which ones to use and when can be confusing at first. Thankfully Angular employs a hierarchical system for how it uses the different injectors.
When the Dependency Injection framework in Angular needs to find a class that is being injected into a component, it starts by looking at the @Component
operator-level injector. If the requested class cannot be found there, Angular moves on to the @Injectable
operator level and trys to find the class being referred to. If Angular still cannot find the class being searched for at this level, Angular moves on to looking at the@NgModule
operator level to see if the class is referenced there.
Example
Let’s have a look at an example of how this works. If we have a component that needs a service to be injected, we use the following code:
import { AppPage } from './app.po'; import { browser, logging } from 'protractor'; describe('workspace-project App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getTitleText()).toEqual('Client-Contacts-Manager-Angular app is running!'); }); afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); });
In this ClientPageComponent
, we are injecting ClientService in the constructor. Then we can use the save()
...