Dependency Injection trong angular - Bài 1 - Các khái niệm

·

1 min read

Dependency: Đối tượng mà được inject vào constructor của service, component, directive, pipe ...

@Injectable: Decorator thông báo cho angular biết nó có thể được inject vào constructor của thằng muốn dùng nó, hay nó sẽ là dependency

Injector: Injector chịu trách nhiệm khởi tạo dependency và đưa nó vào component hoặc service.

Provider: mô tả cách tạo ra dependency, Injector sẽ dựa vào đây để khởi tạo dependecy

DI Tokens: Có thể là 1 type, 1 string hoặc 1 instance của InjectionToken, Injector sẽ dựa vào nó để xác định provider nào để tạo instance depencency, sau đó dựa vào công thức của provider cũng cấp để tạo instance của dependency

@Inject(): Một constructor decorator, thông báo cho angular ta muốn inject 1 dependency vào, nếu muốn inject 1 service mà không dùng decorator @Injectable cho service thì ra có thể dùng @Inject() và đưa service đấy vào.