DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Step-by-Step Guide: Application Using NestJs and Angular
  • Understanding the Dependency Injection Lifecycle: Singleton, Scoped, and Transient With Detailed Examples
  • jQuery vs. Angular: Common Differences You Must Know
  • Angular Best Practices For Developing Efficient and Reliable Web Applications

Trending

  • Two AI Agents, One Database: Solving Concurrent Updates With Optimistic Locking
  • Building a Windows App for a Resilient SSH SOCKS Proxy and Selective Browser Routing
  • Build Production-Ready AI Phone Agents: Infrastructure, Models, and Telephony
  • 5 Mistakes Companies Make When Working With Staff Engineers

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Defining Implementations of Services: Dependency Injection in Angular

Defining Implementations of Services: Dependency Injection in Angular

By 
Javier Santos
·
Mar. 09, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

I was working on a practical project using Angular 8, where I was creating a service and thinking more about how to implement SOLID principles. I decided to have an interface to define my service and a class to implement the logic. Everything was okay with that design, but a question came to my mind, "How can I implement dependency injection with my Angular component?"

In this example, I am going to use an abstract class, Let's create an abstract class, named IGreetingsService. This will be used as an Interface with a greeting method.

TypeScript
 




x


 
1
export abstract class IGreetingsService {
2
  constructor() { }
3
  abstract greeting(): String;
4
}



Now, let's create a class, GreetingsServiceImpl. This class implements the  IGreetingsService  abstract class.

TypeScript
 




xxxxxxxxxx
1


 
1
export class GreetingsServiceImpl implements IGreetingsService {
2
  constructor() { }
3
  greeting(): String{
4
    return "Pruebaa";
5
  };
6
}



At this point, we have a regular class to use as a service, but we need to add the annotation @Injectable. We have to put it at IGreetingsService.

TypeScript
 




x
10


 
1
@Injectable({
2
  providedIn: 'root', 
3
   useClass: GreetingsServiceImpl,
4
})
5
export abstract class IGreetingsService {
6
 
          
7
  constructor() { }
8
 
          
9
  abstract greeting(): String;
10
}


The magic is at the property useClass. This class is used by the Angular framework to know what concrete class has to use for dependency injection when you are using theIGreetingsService abstract class.  So we are ready to use our service into an angular component.

TypeScript
 




xxxxxxxxxx
1
12


 
1
@Component({
2
  selector: 'my-app',
3
  templateUrl: './app.component.html',
4
  styleUrls: [ './app.component.css' ]
5
})
6
export class AppComponent  {
7
  name: String;
8
  constructor(private service: IGreetingsService ) {
9
    this.name = this.service.greeting();
10
  }
11
   
12
}



At the moment, to create an instance of the AppComponent, Angular automatically creates an instance of GreetingsServiceImpl , instead of IGreetingsService. (Remember IGreetingsService is an abstract class).

This approach can help you in several situations; for example, think about a service using REST services to get some data, but now there is a new requirement, and you need to get the same data from session storage or local storage. You can create a new class implementing your abstract class and update the property useClass to refer to your new class. Another situation would be if you needed a different implementation on production environments and testing environments.

You can find the complete source code here:  https://stackblitz.com/edit/angular8-injectiondependency-interface.

A final note, you can define a provider in the component definition annotation to inject a specific implementation of your service. 

TypeScript
 




x


 
1
@Component({
2
  selector: 'my-app',
3
  templateUrl: './app.component.html',
4
  styleUrls: [ './app.component.css' ],
5
  providers :[{ provide: IGreetingsService, useClass: GreetingsServiceImpl }]
6
})



Further Reading

  • Angular: Everything You Need to Know [Tutorials].
  • About Dependency Injection.
Dependency injection AngularJS Implementation

Opinions expressed by DZone contributors are their own.

Related

  • Step-by-Step Guide: Application Using NestJs and Angular
  • Understanding the Dependency Injection Lifecycle: Singleton, Scoped, and Transient With Detailed Examples
  • jQuery vs. Angular: Common Differences You Must Know
  • Angular Best Practices For Developing Efficient and Reliable Web Applications

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook