-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDependency-Injection-DI-Examples
302 lines (238 loc) · 7.12 KB
/
Dependency-Injection-DI-Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// Dependency Injection (DI) Examples
// Example 1: Basic DI with LoggerService
// app.ts
import { Component, Injectable, InjectionToken, Injector, Inject, Optional, NgModule, forwardRef } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { BehaviorSubject, Observable, of } from 'rxjs';
//Basic DI with LoggerService
@Injectable({ providedIn: 'root' })
export class LoggerService {
log(message: string) {
console.log(`[Logger]: ${message}`);
}
}
@Component({
selector: 'app-home',
standalone: true,
template: `
<h2>Home Component</h2>
<button (click)="logMessage()">Log Message</button>
`
})
export class HomeComponent {
constructor(private loggerService: LoggerService) {} // Example 1: Constructor Injection
logMessage() {
this.loggerService.log('Button clicked!');
}
}
// Example 2: (Standalone): Standalone Component with DI
@Component({
selector: 'app-standalone',
standalone: true,
template: `
<h2>Standalone Component</h2>
<button (click)="logMessage()">Log</button>
`,
providers: [LoggerService]
})
export class StandaloneComponent {
private loggerService = inject(LoggerService); // Example 1: inject()
logMessage() {
this.loggerService.log('Standalone Component Log');
}
}
// Example 3: Injectable with providedIn: 'root'
@Injectable({ providedIn: 'root' })
export class DataService {
getData() {
return 'Hello from DataService!';
}
}
// Example 4: providedIn: 'any'
@Injectable({ providedIn: 'any' })
export class AuthService {
isAuthenticated = false;
toggleAuth() {
this.isAuthenticated = !this.isAuthenticated;
}
}
// Example 5: Injector Usage
@Component({
selector: 'app-injector-example',
standalone: true,
template: `
<h2>Injector Example</h2>
<button (click)="logData()">Log Data</button>
`
})
export class InjectorExampleComponent {
constructor(private injector: Injector) {}
logData() {
const dataService = this.injector.get(DataService); // Example 5
console.log(dataService.getData());
}
}
// Example 6: Hierarchical DI
@Component({
selector: 'app-child',
standalone: true,
template: `
<h2>Child Component</h2>
<p>Data: {{ dataService.getData() }}</p>
`,
providers: [DataService] // Example 6: Component-level provider
})
export class ChildComponent {
constructor(private dataService: DataService) {}
}
// Example 7: @Inject with InjectionToken
export const API_URL = new InjectionToken<string>('API_URL');
@Injectable({ providedIn: 'root' })
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) { // Example 10
console.log('API URL:', this.apiUrl);
}
getUrl() {
return this.apiUrl;
}
}
// Example 8: Multi-Providers
export const MULTI_SERVICE = new InjectionToken<string[]>('MULTI_SERVICE');
@Injectable({ providedIn: 'root' })
export class ServiceA {
getData() { return 'ServiceA Data'; }
}
@Injectable({ providedIn: 'root' })
export class ServiceB {
getData() { return 'ServiceB Data'; }
}
// Example 9: Abstract Class with DI
export abstract class AbstractLoggerService {
abstract log(message: string): void;
}
@Injectable({ providedIn: 'root' })
export class ConsoleLoggerService extends AbstractLoggerService {
log(message: string) { console.log('Console Logger:', message); } // Example 12
}
// Example 10: Token-Based Provider
export const CONFIG = new InjectionToken<{ apiUrl: string }>('config');
// Example 11: Factory Provider
export function apiServiceFactory(logger: LoggerService) {
return new ApiService(logger); // Example 17
}
@Injectable({ providedIn: 'root' })
export class FactoryApiService {
constructor(private logger: LoggerService, @Inject(API_URL) private apiUrl: string) {}
logUrl() {
this.logger.log(`Factory API URL: ${this.apiUrl}`);
}
}
// Example 12: Optional Dependency
@Component({
selector: 'app-optional-example',
standalone: true,
template: `
<h2>Optional Dependency</h2>
<p>{{ logger ? 'Logger available' : 'No logger' }}</p>
`
})
export class OptionalExampleComponent {
constructor(@Optional() private logger?: LoggerService) {} // Example 18
}
// Example 13: DI in Standalone Component
@Component({
selector: 'app-standalone-di',
standalone: true,
template: `
<h2>Standalone DI</h2>
<p>Data: {{ dataService.getData() }}</p>
`,
providers: [DataService] // Example 27
})
export class StandaloneDiComponent {
private dataService = inject(DataService);
}
// Example 14: Override Service at Component Level
@Injectable({ providedIn: 'root' })
export class RealDataService {
getData() { return 'Real Data'; }
}
@Injectable()
export class MockDataService {
getData() { return 'Mock Data'; }
}
@Component({
selector: 'app-override-example',
standalone: true,
template: `
<h2>Override Example</h2>
<p>Data: {{ dataService.getData() }}</p>
`,
providers: [{ provide: RealDataService, useClass: MockDataService }] // Example 30
})
export class OverrideExampleComponent {
constructor(private dataService: RealDataService) {}
}
// Example 15: Circular Dependency Handling
@Injectable({ providedIn: 'root' })
export class ServiceOne {
constructor(@Inject(forwardRef(() => ServiceTwo)) private serviceTwo: ServiceTwo) {}
}
@Injectable({ providedIn: 'root' })
export class ServiceTwo {
constructor(@Inject(forwardRef(() => ServiceOne)) private serviceOne: ServiceOne) {}
}
// Example 16: Injection Context with inject()
@Component({
selector: 'app-context-example',
standalone: true,
template: `
<h2>Injection Context</h2>
<button (click)="logMessage()">Log</button>
`,
providers: [LoggerService]
})
export class ContextExampleComponent {
private loggerService = inject(LoggerService); // Example 38a
logMessage() {
this.loggerService.log('Context Example Log');
}
}
// Main App Component
@Component({
selector: 'app-root',
standalone: true,
imports: [
HomeComponent,
StandaloneComponent,
InjectorExampleComponent,
ChildComponent,
OptionalExampleComponent,
StandaloneDiComponent,
OverrideExampleComponent,
ContextExampleComponent
],
template: `
<h1>Angular Dependency Injection Demo</h1>
<app-home></app-home>
<app-standalone></app-standalone>
<app-injector-example></app-injector-example>
<app-child></app-child>
<app-optional-example></app-optional-example>
<app-standalone-di></app-standalone-di>
<app-override-example></app-override-example>
<app-context-example></app-context-example>
`,
providers: [
{ provide: API_URL, useValue: 'https://api.example.com' }, // Example 10 & 13
{ provide: MULTI_SERVICE, useClass: ServiceA, multi: true }, // Example 11
{ provide: MULTI_SERVICE, useClass: ServiceB, multi: true }, // Example 11
{ provide: AbstractLoggerService, useClass: ConsoleLoggerService }, // Example 12
{ provide: CONFIG, useValue: { apiUrl: 'https://config.example.com' } }, // Example 13
{ provide: FactoryApiService, useFactory: apiServiceFactory, deps: [LoggerService] } // Example 17
]
})
export class AppComponent {}
// Bootstrap the application
bootstrapApplication(AppComponent)
.catch(err => console.error(err));