Trung BìnhAngular iconAngular

Provider strategies `useClass`, `useValue`, `useFactory`, `useExisting` khác nhau thế nào?

useClass tạo instance từ class cụ thể, thường để đổi implementation.

Ví dụ các provider strategy:

typescript
providers: [
  { provide: Logger, useClass: ConsoleLogger },
  { provide: API_URL, useValue: "/api" },
  { provide: SESSION_ID, useFactory: () => crypto.randomUUID() },
  { provide: OLD_LOGGER, useExisting: Logger },
]

useValue cấp object/value có sẵn, useFactory tạo dependency động và có thể inject dependency khác, useExisting alias token này sang token khác để reuse cùng instance.

Xem toàn bộ Angular cùng filter theo level & chủ đề con.

Mở danh sách Angular