Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Essential Angular

You're reading from   Essential Angular Fast paced guide to Front-end web development with Angular

Arrow left icon
Product type Paperback
Published in May 2017
Publisher Packt
ISBN-13 9781788293761
Length 108 pages
Edition 1st Edition
Tools
Arrow right icon
Authors (3):
Arrow left icon
Narwhal Technologies Inc Narwhal Technologies Inc
Author Profile Icon Narwhal Technologies Inc
Narwhal Technologies Inc
Jeff Cross Jeff Cross
Author Profile Icon Jeff Cross
Jeff Cross
Victor Savkin Victor Savkin
Author Profile Icon Victor Savkin
Victor Savkin
Arrow right icon
View More author details
Toc

Dependency Injection

The idea behind dependency injection is very simple. If you have a component that depends on a service, you do not create that service yourself. Instead, you request one in the constructor, and the framework will provide you one. By doing so you can depend on interfaces rather than concrete types. This leads to more decoupled code, which enables testability, and other great things.

Angular comes with a dependency injection system. To see how it can be used, let's look at the following component, which renders a list of talks using the for directive:

@Component({
selector: 'talks-cmp',
template: `
<h2>Talks:</h2>
<talk *ngFor="let t of talks" [talk]="t"></talk>
`
})
class TalksCmp {
constructor() { //..get the data }
}

Let’s mock up a simple service that will give us the data:

class TalksAppBackend {
fetchTalks() {
...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime