Alias Provider: useExisting

As we know that Angular provides different types of providers such as class provider, alias provider, value provider and factory provider. So in this article we will learn about Alias provider step by step with example.

useExisting is an alias provider that assigns one token to another.

providers: [ 
	    Angular7Service,
	    { provide: Angular6Service, useExisting: Angular7Service }
	] 

Mapping can only be done if both tokens have the same interface.

The alias provider is used in case we injected a service into a component or any other service and has become old and now we want to use a new service without changing the code. From the above configuration, wherever we injected Angular7Service, now they will use Angular7Service.

Now we will create an example for Alias Provider: useExisting and Folder structure for this example as shown below.

src
├── app
│   ├── services
│   │   ├── Angular6.service.ts
│   │   ├── Angular7.service.ts
│   ├── course.component.ts
│   ├── app.component.ts
│   ├── app.module.ts

Angular6.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class Angular6Service  {
	CourseName = 'Angular 6';
}

Angular7.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class Angular7Service {
	CourseName = 'Angular 7';
}

course.component.ts

import { Component, OnInit } from '@angular/core';
import { Angular6Service } from './services/Angular6.service';
import { Angular7Service } from './services/Angular7.service';

@Component({
    selector: 'course',
    providers: [ 
	    Angular7Service,
	    { provide: Angular6Service, useExisting: Angular7Service }
	],     
    template: `
	     <h3>Currently I work on {{CourseName}} </h3>
	`
})
export class CourseComponent implements OnInit {
	CourseName: string;
	constructor(private courseService: Angular6Service) { }
	ngOnInit() {
		debugger;
		this.CourseName = this.courseService.CourseName;
	}
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
          <course></course>
  `
})
export class AppComponent {
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import { CourseComponent }  from './course.component';

@NgModule({
  imports: [     
        BrowserModule
  ],
  declarations: [
        AppComponent,
        CourseComponent,
  ],
  providers: [ 
  ],  
  bootstrap: [
        AppComponent
  ]
})
export class AppModule { }

when you run the application, you will get the output as shown below.

sahosoft-Tutorials-Class-Provider-useClass

download demo source code

Alias Provider : useExisting