'How does angular inject parameters into the constructor
When I change the order of injection parameters, the program can still execute normally. Why? This violates JS common sense.
The effect of the following code is the same. But the order of parameters is different.
export class ProductDetailsComponent implements OnInit {
// CartService is a service generated through `ng generate service cart`
// ActivatedRoute form `import { ActivatedRoute } from '@angular/router'`
constructor(private cartService: CartService, private route: ActivatedRoute) {
}
}
export class ProductDetailsComponent implements OnInit {
// CartService is a service generated through `ng generate service cart`
// ActivatedRoute form `import { ActivatedRoute } from '@angular/router'`
constructor(private route: ActivatedRoute, private cartService: CartService) {
}
}
I found some relevant information
https://angular.io/guide/what-is-angular#dependency-injection
Document said : Dependency injection lets you declare the dependencies of your TypeScript classes without taking care of their instantiation.
Although the author said he didn't need to care, I want to know how he did it
Solution 1:[1]
@Component, and @Injectable will mark to DI that the first parameter of the constructor of the class. If there are more parameters, it will give the correct order of the constructor parameters so DI knows how to inject the correct instances.
If you want to more information, i think you need to read source code of Angular: https://github.com/angular/angular/blob/4fa530757b13a67586d17aa4dafb72c91f501016/packages/compiler/src/injectable_compiler_2.ts#L28
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hu?n Nguy?n Xuân |
