Slide 1

Slide 1 text

Dependency Injection in Angular Marko Stanimirović

Slide 2

Slide 2 text

Marko Stanimirović @MarkoStDev ★ Sr. Frontend Engineer at JobCloud ★ NgRx Core Team Member ★ Angular Belgrade Organizer ★ Hobby Musician

Slide 3

Slide 3 text

Marko Stanimirović @MarkoStDev ★ Sr. Frontend Engineer at JobCloud ★ NgRx Core Team Member ★ Angular Belgrade Organizer ★ Hobby Musician ★ Google Developer Expert in Angular

Slide 4

Slide 4 text

What is Dependency Injection?

Slide 5

Slide 5 text

“DI is a design pattern that makes an object independent of its dependencies by decoupling its usage from its creation.”

Slide 6

Slide 6 text

Improves testability, scalability and maintainability Reduces tight coupling

Slide 7

Slide 7 text

class UsersService { private usersResource = new HttpUsersResource(); private logger = new ServerLogger(); } Without Dependency Injection

Slide 8

Slide 8 text

class UsersService { private usersResource = new HttpUsersResource(); private logger = new ServerLogger(); } Tightly coupled Without Dependency Injection

Slide 9

Slide 9 text

class UsersService { constructor( private usersResource: UsersResource, private logger: Logger ) {} } With Dependency Injection

Slide 10

Slide 10 text

class UsersService { constructor( private usersResource: UsersResource, private logger: Logger ) {} } With Dependency Injection Loosely coupled

Slide 11

Slide 11 text

Injection Scopes in Angular

Slide 12

Slide 12 text

Injection Scopes in Standalone Angular Apps

Slide 13

Slide 13 text

Injection Scopes in Standalone Angular Apps Root

Slide 14

Slide 14 text

Injection Scopes in Standalone Angular Apps Route Root

Slide 15

Slide 15 text

Injection Scopes in Standalone Angular Apps Element Route Root (Component / Directive)

Slide 16

Slide 16 text

Root Providers

Slide 17

Slide 17 text

Providing Service at the Root Level - #1 Way class UsersService { ./ ... }

Slide 18

Slide 18 text

Providing Service at the Root Level - #1 Way @Injectable({ providedIn: 'root' }) class UsersService { ./ ... }

Slide 19

Slide 19 text

Providing Service at the Root Level - #1 Way @Injectable({ providedIn: 'root' }) class UsersService { ./ ... } @Component(** **. */) class UserDetailsComponent { constructor(private usersService: UsersService) {} }

Slide 20

Slide 20 text

Providing Service at the Root Level - #2 Way @Injectable() class UsersService { ./ ... } bootstrapApplication(AppComponent, { providers: [UsersService], });

Slide 21

Slide 21 text

Route Providers

Slide 22

Slide 22 text

Providing Service at the Route Level const userRoutes: Route[] = [ { path: '', component: UsersShellComponent, children: [ { path: '', component: UserListComponent }, { path: ':id', component: UserDetailsComponent }, ], }, ];

Slide 23

Slide 23 text

Providing Service at the Route Level const userRoutes: Route[] = [ { path: '', component: UsersShellComponent, providers: [UsersService], children: [ { path: '', component: UserListComponent }, { path: ':id', component: UserDetailsComponent }, ], }, ];

Slide 24

Slide 24 text

Providing Service at the Route Level const userRoutes: Route[] = [ { path: '', component: UsersShellComponent, providers: [UsersService], children: [ { path: '', component: UserListComponent }, { path: ':id', component: UserDetailsComponent }, ], }, ];

Slide 25

Slide 25 text

Element Providers

Slide 26

Slide 26 text

Providing Service at the Component Level @Component({ selector: 'app-user-details', standalone: true, template: ` ./app-user-form> ./ng-content> `, imports: [UserFormComponent], }) class UserDetailsComponent { constructor(readonly usersService: UsersService) {} }

Slide 27

Slide 27 text

Providing Service at the Component Level @Component({ selector: 'app-user-details', standalone: true, template: ` ./app-user-form> ./ng-content> `, providers: [UsersService], imports: [UserFormComponent], }) class UserDetailsComponent { constructor(readonly usersService: UsersService) {} }

Slide 28

Slide 28 text

Providing Service at the Component Level @Component({ selector: 'app-user-details', standalone: true, template: ` ./app-user-form> ./ng-content> `, providers: [UsersService], imports: [UserFormComponent], }) class UserDetailsComponent { constructor(readonly usersService: UsersService) {} }

Slide 29

Slide 29 text

Providing Service at the Component Level @Component({ selector: 'app-user-details', standalone: true, template: ` ./app-user-form> ./ng-content> `, viewProviders: [UsersService], imports: [UserFormComponent], }) class UserDetailsComponent { constructor(readonly usersService: UsersService) {} }

Slide 30

Slide 30 text

Providing Service at the Component Level @Component({ selector: 'app-user-details', standalone: true, template: ` ./app-user-form> ./ng-content> `, viewProviders: [UsersService], imports: [UserFormComponent], }) class UserDetailsComponent { constructor(readonly usersService: UsersService) {} }

Slide 31

Slide 31 text

Dependency Resolution in Angular

Slide 32

Slide 32 text

Element Injector viewProviders @Inject(UsersService) providers UserDetailsComponent

Slide 33

Slide 33 text

Element Injector viewProviders @Inject(UsersService) providers UserDetailsComponent

Slide 34

Slide 34 text

Element Injector viewProviders @Inject(UsersService) providers UserDetailsComponent

Slide 35

Slide 35 text

Element Injector viewProviders @Inject(UsersService) providers Element Injector viewProviders providers AppComponent UserDetailsComponent

Slide 36

Slide 36 text

Element Injector viewProviders @Inject(UsersService) providers Element Injector viewProviders providers AppComponent UserDetailsComponent

Slide 37

Slide 37 text

Element Injector viewProviders @Inject(UsersService) providers Element Injector viewProviders providers AppComponent Route Injector providers UserDetailsComponent

Slide 38

Slide 38 text

Element Injector viewProviders @Inject(UsersService) providers Root Injector providers Element Injector viewProviders providers AppComponent Route Injector providers UserDetailsComponent

Slide 39

Slide 39 text

Element Injector viewProviders @Inject(UsersService) providers Root Injector providers Element Injector viewProviders providers AppComponent Route Injector providers UserDetailsComponent

Slide 40

Slide 40 text

Resolution Modifiers

Slide 41

Slide 41 text

Optional Modifier

Slide 42

Slide 42 text

Optional Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Optional() private usersService.: UsersService) {} }

Slide 43

Slide 43 text

Optional Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Optional() private usersService.: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent @Optional() @Inject(UsersService)

Slide 44

Slide 44 text

Optional Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Optional() private usersService.: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent Element Injector viewProviders providers AppComponent Route Injector providers Root Injector providers @Optional() @Inject(UsersService) null

Slide 45

Slide 45 text

SkipSelf Modifier

Slide 46

Slide 46 text

SkipSelf Modifier @Component(** **. */) class UserDetailsComponent { constructor(@SkipSelf() private usersService: UsersService) {} }

Slide 47

Slide 47 text

SkipSelf Modifier @Component(** **. */) class UserDetailsComponent { constructor(@SkipSelf() private usersService: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent Element Injector viewProviders providers AppComponent Route Injector providers Root Injector providers @SkipSelf() @Inject(UsersService) search starts here

Slide 48

Slide 48 text

Self Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Self() private usersService: UsersService) {} }

Slide 49

Slide 49 text

Self Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Self() private usersService: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent @Self() @Inject(UsersService)

Slide 50

Slide 50 text

Self Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Self() private usersService: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent @Self() @Inject(UsersService)

Slide 51

Slide 51 text

Host Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Host() private usersService: UsersService) {} }

Slide 52

Slide 52 text

Host Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Host() private usersService: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent @Host() @Inject(UsersService)

Slide 53

Slide 53 text

Host Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Host() private usersService: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent @Host() @Inject(UsersService)

Slide 54

Slide 54 text

Host Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Host() private usersService: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent @Host() @Inject(UsersService) Element Injector viewProviders providers AppComponent

Slide 55

Slide 55 text

Host Modifier @Component(** **. */) class UserDetailsComponent { constructor(@Host() private usersService: UsersService) {} } Element Injector viewProviders providers UserDetailsComponent @Host() @Inject(UsersService) Element Injector viewProviders providers AppComponent

Slide 56

Slide 56 text

Injection Tokens

Slide 57

Slide 57 text

Creating Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme');

Slide 58

Slide 58 text

Creating Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); constant value type description

Slide 59

Slide 59 text

Providing Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); bootstrapApplication(AppComponent, { providers: [ ], }); providing at the root level

Slide 60

Slide 60 text

Providing Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); bootstrapApplication(AppComponent, { providers: [APP_THEME ], });

Slide 61

Slide 61 text

Providing Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); bootstrapApplication(AppComponent, { providers: [{ }], });

Slide 62

Slide 62 text

Providing Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); bootstrapApplication(AppComponent, { providers: [{ provide: APP_THEME }], });

Slide 63

Slide 63 text

Providing Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); bootstrapApplication(AppComponent, { providers: [{ provide: APP_THEME, useValue: 'light' }], });

Slide 64

Slide 64 text

Providing Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); bootstrapApplication(AppComponent, { providers: [{ provide: APP_THEME, useFactory: appThemeFactory }], }); function appThemeFactory() { return localStorage.getItem('theme') .? 'light'; }

Slide 65

Slide 65 text

Injecting Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); bootstrapApplication(AppComponent, { providers: [{ provide: APP_THEME, useFactory: appThemeFactory }], }); @Component(** **. */) class SideMenuComponent { constructor( ) {} }

Slide 66

Slide 66 text

Injecting Injection Token const APP_THEME = new InjectionToken<'light' | 'dark'>('Application Theme'); bootstrapApplication(AppComponent, { providers: [{ provide: APP_THEME, useFactory: appThemeFactory }], }); @Component(** **. */) class SideMenuComponent { constructor(@Inject(APP_THEME) theme: 'light' | 'dark') {} }

Slide 67

Slide 67 text

Providing Injection Token - Tree Shakeable Way const APP_THEME = new InjectionToken('Application Theme', { });

Slide 68

Slide 68 text

Providing Injection Token - Tree Shakeable Way const APP_THEME = new InjectionToken('Application Theme', { providedIn: 'root', factory: () .> localStorage.getItem('theme') .? 'light', });

Slide 69

Slide 69 text

Providing Injection Token - Tree Shakeable Way const APP_THEME = new InjectionToken('Application Theme', { providedIn: 'root', factory: () .> localStorage.getItem('theme') .? 'light', }); @Component(** **. */) class SideMenuComponent { constructor(@Inject(APP_THEME) theme: 'light' | 'dark') {} }

Slide 70

Slide 70 text

inject Function

Slide 71

Slide 71 text

Constructor-Based DI vs inject @Component({ ** **. */ }) export class UserDetailsComponent { constructor( private usersService: UsersService, private route: ActivatedRoute ) {} }

Slide 72

Slide 72 text

Constructor-Based DI vs inject @Component({ ** **. */ }) export class UserDetailsComponent { constructor( private usersService: UsersService, private route: ActivatedRoute ) {} } @Component({ ** **. */ }) export class UserDetailsComponent { private usersService = inject(UsersService); private route = inject(ActivatedRoute); }

Slide 73

Slide 73 text

Constructor-Based DI vs inject @Component({ ** **. */ }) export class UserDetailsComponent { constructor( private usersService: UsersService, private route: ActivatedRoute ) {} } @Component({ ** **. */ }) export class UserDetailsComponent { private usersService = inject(UsersService); private route = inject(ActivatedRoute); } token

Slide 74

Slide 74 text

Resolution Modifiers with inject @Component({ ** **. */ }) export class UserDetailsComponent { private usersService = inject(UsersService, { self: true, optional: true }); }

Slide 75

Slide 75 text

Resolution Modifiers with inject @Component({ ** **. */ }) export class UserDetailsComponent { private usersService = inject(UsersService, { self: true, optional: true }); } config

Slide 76

Slide 76 text

Factories with inject

Slide 77

Slide 77 text

Factories with inject const ID_ROUTE_PARAM = new InjectionToken('ID Route Parameter Observable', { factory() { }, });

Slide 78

Slide 78 text

Factories with inject const ID_ROUTE_PARAM = new InjectionToken('ID Route Parameter Observable', { factory() { const route = inject(ActivatedRoute); }, });

Slide 79

Slide 79 text

Factories with inject const ID_ROUTE_PARAM = new InjectionToken('ID Route Parameter Observable', { factory() { const route = inject(ActivatedRoute); return route.params.pipe( map((params) .> params['id']), filter(Boolean), distinctUntilChanged() ); }, });

Slide 80

Slide 80 text

Base Classes with inject

Slide 81

Slide 81 text

Base Classes with Constructor-Based DI abstract class EntityResource { ./ ... }

Slide 82

Slide 82 text

Base Classes with Constructor-Based DI abstract class EntityResource { protected constructor( protected http: HttpClient, protected apiUrl: string, protected uri: string ) {} ./ ... }

Slide 83

Slide 83 text

Base Classes with Constructor-Based DI abstract class EntityResource { protected constructor( protected http: HttpClient, protected apiUrl: string, protected uri: string ) {} ./ ... } @Injectable({ providedIn: 'root' }) class UsersResource extends EntityResource { }

Slide 84

Slide 84 text

Base Classes with Constructor-Based DI abstract class EntityResource { protected constructor( protected http: HttpClient, protected apiUrl: string, protected uri: string ) {} ./ ... } @Injectable({ providedIn: 'root' }) class UsersResource extends EntityResource { constructor( http: HttpClient, @Inject(API_URL) apiUrl: string ) { super(http, apiUrl, 'users'); } }

Slide 85

Slide 85 text

Base Classes with inject abstract class EntityResource { ./ ... }

Slide 86

Slide 86 text

Base Classes with inject abstract class EntityResource { protected http = inject(HttpClient); protected apiUrl = inject(API_URL); protected constructor(protected uri: string) {} ./ ... }

Slide 87

Slide 87 text

Base Classes with inject abstract class EntityResource { protected http = inject(HttpClient); protected apiUrl = inject(API_URL); protected constructor(protected uri: string) {} ./ ... } @Injectable({ providedIn: 'root' }) class UsersResource extends EntityResource { constructor() { super('users'); } }

Slide 88

Slide 88 text

Advanced DI Techniques

Slide 89

Slide 89 text

Providing Logger Based on Environment

Slide 90

Slide 90 text

Providing Logger Based on Environment @Injectable({ providedIn: 'root', }) abstract class Logger { abstract log(message: string): void; abstract error(message: string): void; }

Slide 91

Slide 91 text

Providing Logger Based on Environment @Injectable({ providedIn: 'root', }) abstract class Logger { abstract log(message: string): void; abstract error(message: string): void; } @Injectable({ providedIn: 'root' }) class ServerLogger extends Logger { ./ ... } @Injectable({ providedIn: 'root' }) class ConsoleLogger extends Logger { ./ ... }

Slide 92

Slide 92 text

Providing Logger Based on Environment @Injectable({ providedIn: 'root', useFactory: () .> environment.production ? inject(ServerLogger) : inject(ConsoleLogger), }) abstract class Logger { abstract log(message: string): void; abstract error(message: string): void; } @Injectable({ providedIn: 'root' }) class ServerLogger extends Logger { ./ ... } @Injectable({ providedIn: 'root' }) class ConsoleLogger extends Logger { ./ ... }

Slide 93

Slide 93 text

Providing Logger Based on Environment @Injectable({ providedIn: 'root', useFactory: () .> environment.production ? inject(ServerLogger) : inject(ConsoleLogger), }) abstract class Logger { abstract log(message: string): void; abstract error(message: string): void; } @Injectable({ providedIn: 'root' }) class ServerLogger extends Logger { ./ ... } @Injectable({ providedIn: 'root' }) class ConsoleLogger extends Logger { ./ ... } @Injectable({ providedIn: 'root' }) class UsersService { constructor(private readonly logger: Logger) {} }

Slide 94

Slide 94 text

Example from @ngrx/component package

Slide 95

Slide 95 text

tick-scheduler.ts @Injectable({ providedIn: 'root', }) abstract class TickScheduler { abstract schedule(): void; }

Slide 96

Slide 96 text

tick-scheduler.ts @Injectable({ providedIn: 'root', }) abstract class TickScheduler { abstract schedule(): void; } @Injectable({ providedIn: 'root' }) class AnimationFrameTickScheduler extends TickScheduler { ./ ... } class NoopTickScheduler extends TickScheduler { schedule(): void {} }

Slide 97

Slide 97 text

tick-scheduler.ts @Injectable({ providedIn: 'root', useFactory: () .> { const zone = inject(NgZone); return isNgZone(zone) ? new NoopTickScheduler() : inject(AnimationFrameTickScheduler); }, }) abstract class TickScheduler { abstract schedule(): void; } @Injectable({ providedIn: 'root' }) class AnimationFrameTickScheduler extends TickScheduler { ./ ... } class NoopTickScheduler extends TickScheduler { schedule(): void {} }

Slide 98

Slide 98 text

tick-scheduler.ts @Injectable({ providedIn: 'root', useFactory: () .> { const zone = inject(NgZone); return isNgZone(zone) ? new NoopTickScheduler() : inject(AnimationFrameTickScheduler); }, }) abstract class TickScheduler { abstract schedule(): void; } @Injectable({ providedIn: 'root' }) class AnimationFrameTickScheduler extends TickScheduler { ./ ... } class NoopTickScheduler extends TickScheduler { schedule(): void {} }

Slide 99

Slide 99 text

Angular DI Under the Hood

Slide 100

Slide 100 text

Scan project files

Slide 101

Slide 101 text

Scan project files Find all classes with Angular-specific decorators @Injectable() @Component() @Directive() @Pipe()

Slide 102

Slide 102 text

Scan project files Find all classes with Angular-specific decorators Preserve information about constructor parameter types @Injectable() @Component() @Directive() @Pipe()

Slide 103

Slide 103 text

Scan project files Find all classes with Angular-specific decorators Preserve information about constructor parameter types Transpile TypeScript to JavaScript @Injectable() @Component() @Directive() @Pipe()

Slide 104

Slide 104 text

users.service.ts @Injectable({ providedIn: 'root' }) class UsersService { constructor( private usersResource: UsersResource, private logger: Logger ) {} }

Slide 105

Slide 105 text

users.service.ts @Injectable({ providedIn: 'root' }) class UsersService { constructor( private usersResource: UsersResource, private logger: Logger ) {} } class UsersService { constructor(usersResource, logger) { this.usersResource = usersResource; this.logger = logger; } } UsersService.ɵfac = function UsersService_Factory() { return new UsersService( ɵɵinject(UsersResource), ɵɵinject(Logger) ); }; UsersService.ɵprov = ɵɵdefineInjectable({ token: UsersService, factory: UsersService.ɵfac, providedIn: 'root' }); Compiled Output

Slide 106

Slide 106 text

users.service.ts @Injectable({ providedIn: 'root' }) class UsersService { constructor( private usersResource: UsersResource, private logger: Logger ) {} } class UsersService { constructor(usersResource, logger) { this.usersResource = usersResource; this.logger = logger; } } UsersService.ɵfac = function UsersService_Factory() { return new UsersService( ɵɵinject(UsersResource), ɵɵinject(Logger) ); }; UsersService.ɵprov = ɵɵdefineInjectable({ token: UsersService, factory: UsersService.ɵfac, providedIn: 'root' }); Compiled Output

Slide 107

Slide 107 text

users.service.ts @Injectable({ providedIn: 'root' }) class UsersService { constructor( private usersResource: UsersResource, private logger: Logger ) {} } class UsersService { constructor(usersResource, logger) { this.usersResource = usersResource; this.logger = logger; } } UsersService.ɵfac = function UsersService_Factory() { return new UsersService( ɵɵinject(UsersResource), ɵɵinject(Logger) ); }; UsersService.ɵprov = ɵɵdefineInjectable({ token: UsersService, factory: UsersService.ɵfac, providedIn: 'root' }); Compiled Output

Slide 108

Slide 108 text

users.service.ts @Injectable({ providedIn: 'root' }) class UsersService { constructor( private usersResource: UsersResource, private logger: Logger ) {} } class UsersService { constructor(usersResource, logger) { this.usersResource = usersResource; this.logger = logger; } } UsersService.ɵfac = function UsersService_Factory() { return new UsersService( ɵɵinject(UsersResource), ɵɵinject(Logger) ); }; UsersService.ɵprov = ɵɵdefineInjectable({ token: UsersService, factory: UsersService.ɵfac, providedIn: 'root' }); Compiled Output

Slide 109

Slide 109 text

Summary

Slide 110

Slide 110 text

DI mechanism is one of the most powerful features of the Angular Framework! DI gives the ability to write loosely coupled and reusable code that is easier to test, scale, and maintain.

Slide 111

Slide 111 text

Marko Stanimirović @MarkoStDev Thank You!