The documentation on Angular defines dependency injection (DI) as, “a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.”
Essentially it is a mechanism in which the components of you Angular application resolve any dependencies related to services or components required by your component.
As you progress through the course, these concepts will be explored more fully along with examples of implementations in code to give you hands-on practice and reinforce your understanding.
Introduction to Dependency Injection (DI)
• Maintaining a component's state
• Providing components to other components, as required
Using Dependency Injection
In our lab scenario, we will be creating an interface to some data that will come from GitHub. We are building a GitHub search component for the lab. This interface will be used in a service and that service will become an injectable component available for use in other components.
In the last lab step in this module, you will inject that service into your application module and use it to access the functionality of the Git search. In this way, our service is a stand-alone, testable, and reusable component but not only that, we don't need to worry about instantiating it in our client code. Angular takes care of this for us automatically. An added benefit is that the service may contain data that becomes shareable among all components that inject it. It is a singleton.
This diagram depicts the integration of the various components.

To use a service
Now that we have our component generated, we are going to
inject the service that we created in Module 2 into our component. This will be
very similar to what you did when you were working with the app.component, except we are going to include an
additional method that we will be using later to change the search query
dynamically.
1.
Open up your src/app/git-search/git-search.component.ts file in Visual Studio Code.
2.
Import the service into your component by adding
an import statement to the top block of code. We also need to import the
interface for GitSearch that we made in the previous
module.
import
{ GitSearchService } from
'../git-search.service'
import
{ GitSearch } from
'../git-search'
3.
Then, go ahead and inject the service in the
constructor function.
constructor(private GitSearchService: GitSearchService) { }
4.
Let's go ahead and make a variable to hold the
search results to convey to the view. To do so, we'll create a type declaration
above the constructor for a searchResults variable
with the type of GitSearch.
export
class GitSearchComponent implements OnInit {
searchResults: GitSearch;
constructor(private GitSearchService: GitSearchService)
{ }
When you declare variable types above a constructor,
TypeScript automatically creates a variable scoped to this.
5.
You'll notice that the ngOnInit() lifecycle method
has already been created for you. Let's go ahead and add the same code that we
had in the app.component.ts
in the previous module that used the service to display an alert. Open up your app.component.ts and copy the
contents of the ngOnInit() function, then paste that
into the ngOnInit() method of git-search.component.ts.
ngOnInit() {
this.GitSearchService.gitSearch('angular').then((response)
=> {
alert("Total
Libraries Found:" + response.total_count);
}, (error) => {
alert("Error:
" + error.statusText)
})
}
Go ahead and empty the ngOnInit
function in app.component.ts
like so:
ngOnInit() { }
6.
Now, let's modify the inner function of .then() to store the search response in the
this.searchResults variable.
ngOnInit() {
this.GitSearchService.gitSearch('angular').then((response)
=> {
this.searchResults
= results;
}, (error) => {
alert("Error:
" + error.statusText)
})
}
7.
Next we are going to make a second method that
we can call with a search parameter to send a different query string to the
server.
ngOnInit() {
this.GitSearchService.gitSearch('angular').then((response)
=> {
this.searchResults
= results;
}, (error) => {
alert("Error:
" + error.statusText)
})
}
gitSearch
= (query: string) => {
}
8.
Let's copy the method from the ngOnInit()
function, and change 'angular' to query.
ngOnInit() {
this.GitSearchService.gitSearch('angular').then((response)
=> {
this.searchResults
= results;
}, (error) => {
alert("Error:
" + error.statusText)
})
}
gitSearch
= (query: string) => {
this.GitSearchService.gitSearch(query).then((response)
=> {
this.searchResults
= results;
}, (error) => {
alert("Error:
" + error.statusText)
})
}
Now we have a function that we can call to search for whatever
keyword we want in GitHub.
9.
When you're finished, your git-search.component.ts should look
like this:
import
{ Component, OnInit } from
'@angular/core';
import
{ GitSearchService } from
'../git-search.service'
import
{ GitSearch } from
'../git-search'
@Component({
selector: 'app-git-search',
templateUrl:
'./git-search.component.html',
styleUrls:
['./git-search.component.css']
})
export
class GitSearchComponent implements OnInit {
searchResults: GitSearch;
constructor(private GitSearchService: GitSearchService)
{ }
ngOnInit() {
this.GitSearchService.gitSearch('angular').then(
(response) => {
this.searchResults
= response;
}, (error) => {
alert("Error:
" + error.statusText)
})
}
gitSearch = (query)
=> {
this.GitSearchService.gitSearch(query).then(
(response) => {
this.searchResults
= response;
}, (error) => {
alert("Error:
" + error.statusText)
})
}
}
So to recap, we have modified
this component so that the GitSearchService is
injected using dependency injection. We modified ngInit
so that it executes a search for ‘angular’ when the component is initialized,
and we have added a function called gitSearch that
will take an arbitrary query string and perform a search using that value. In
our next task we are going to instantiate our new GitSearchComponent
in our main view component - app.component.ts.