I read the book "Angular for Professionals", just started to master. And I can not understand how it works. There is such a code:

import { Injectable } from "@angular/core"; import { Product } from "./product.model"; import { StaticDataSource } from "./static.datasource"; @Injectable() export class ProductRepository { private products: Product[] = []; private categories: string[] = []; constructor(private dataSource: StaticDataSource) { dataSource.getProducts().subscribe(data => { this.products = data; this.categories = data.map(p => p.category) .filter((c, index, array) => array.indexOf(c) == index).sort(); }); } getProducts(category: string = null): Product[] { return this.products .filter(p => category == null || category == p.category); } getProduct(id: number): Product { return this.products.find(p => p.id == id); } getCategories(): string[] { return this.categories; } } 

In the constructor, a parameter is specified that says that an instance of the type StaticDatasource should come to the designer's input. Which has a getProducts () method. Its code in this situation is not particularly important. I'm interested in how data gets there, because there is no explicit initialization of a variable of type StaticDatasource. Where does he get it from? After all, the annotation in the constructor simply indicates that an object of such and such type should be transferred to the constructor, or did I misunderstand something? Please explain.

1 answer 1

Note that you most likely have registered the StaticDatasource in the module of your component. This is where initialization takes place - in providers. When your component is initialized, DI looks at the type of dependency from the constructor, and injects it from the previously registered array of providers. That's the whole point. You yourself do not need to care how to implement a dependency instance. Plus, the service announced in the module is a singleton for all components of this module. (In fact, not only for these components, but also for the children of the module, but that's another story)