Dependency Injection - quan1997ap/angular-app-note GitHub Wiki
https://blog.angular-university.io/angular-dependency-injection/
https://angular8.hashnode.dev/dependency-injection-trong-angular-bai-3-provider
Có 5 thành phần chính trong Angular Dependency Injection Framework
-
Consumer : nơi mà nhúng service vào. Trong ví dụ của chúng ta là AppComponent
-
Dependency : Những service được nhúng vào component
-
DI Token : Được sinh ra là một dãy ký tự tượng trưng cho ID và là duy nhất khi Service đăng ký là Dependency Injection với Framework
-
Provider : quản lý danh sách các dependencies và token của nó
-
Injector : quản lý việc nhúng các đối tượng Dependency vào các consumer
Cơ chế hoạt động của Dependency như sau:
-
Dependency đăng ký với Provider
-
Sau đó Angular Provider sẽ nhúng các dependency vào các module consumer tương ứng.
-
Consumer sẽ khởi tạo các đối tượng Dependency thông qua constructor.
providedIn
@[Injectable](https://angular.io/api/core/Injectable)({
// declares that this service should be created
// by the root application injector.
providedIn: 'root',
})
The @Injectable() decorator specifies that Angular can use this class in the DI system. The metadata, providedIn: 'root', means that the HeroService is visible throughout the application.
Ý nghĩa
@Injectable()
export class CoursesService() {
http: HttpClient;
constructor(http: HttpClient) {
this.http = http;
}
...
}
This class simply does not know how to create its http dependency. This new version of the class simply receives all the dependencies that it needs as input arguments in the constructor, and that's it!