...

/

Providers in Angular

Providers in Angular

Let's go through all the different approaches for creating providers in Angular.

What is the provider?

So, we’ve had a look at what Injectors are and the various levels of Injectors in Angular, but now we are going to have a look at providers. We have seen them briefly already, but it’s worth having a more in-depth look at them and the role they fulfill in Angular.


The Injector needs a provider to create the instances (versions) of the classes being injected into all the components, services, and directives.


The way this relationship between injector and provider is set up is through a token that the injector uses at runtime to create the required class that the provider needs. So, when our application is running and a class is needed via Dependency Injection, the token that the provider gives makes sure that the class being used is the one with the correct token.

In ClientModule, we can see how ClientService is itself being used as this token:

@NgModule({
  declarations: [ClientPageComponent, ClientFormComponent],
  providers: [ClientService],
  imports: [CommonModule, 
            ReactiveFormsModule, 
            SharedModule, 
            CustomMaterialModule],
})
export class ClientModule {}

Here, ClientService is the token that is being provided to the providers array.

Provider object literal


The provider object literal will allow us to give a more relevant name to our services.


We could also write the name of the service in another way, by using an object to set ClientService as a token for the provider (line 12):

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));
  });
});
Client Contacts Manager Application with ClientService being injected into the module

Why would you use this ...