<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Olia Pankiv on Medium]]></title>
        <description><![CDATA[Stories by Olia Pankiv on Medium]]></description>
        <link>https://medium.com/@olia.pankiv?source=rss-2197d367fb44------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iZ6kH23KEQr839leQziU2Q.jpeg</url>
            <title>Stories by Olia Pankiv on Medium</title>
            <link>https://medium.com/@olia.pankiv?source=rss-2197d367fb44------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:04:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olia.pankiv/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding runInInjectionContext in Angular: How, Why, and When to Use It]]></title>
            <link>https://medium.com/tenantcloud-engineering/understanding-runininjectioncontext-in-angular-how-why-and-when-to-use-it-0328ea3e013f?source=rss-2197d367fb44------2</link>
            <guid isPermaLink="false">https://medium.com/p/0328ea3e013f</guid>
            <dc:creator><![CDATA[Olia Pankiv]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 08:45:21 GMT</pubDate>
            <atom:updated>2025-05-15T09:20:09.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular’s Dependency Injection (DI) system is central to the framework’s architecture, but sometimes you need to access services outside the standard injection contexts. This is where runInInjectionContext comes in - a powerful utility function introduced to solve specific DI challenges.</p><h3>What is runInInjectionContext?</h3><p>runInInjectionContext is a function that allows you to execute code within a specific injection context. It creates a temporary environment where Angular&#39;s DI system is accessible, even in places where it normally wouldn&#39;t be.</p><p>The syntax is straightforward:</p><pre>import { runInInjectionContext } from &#39;@angular/core&#39;;<br><br>runInInjectionContext(injector, () =&gt; {<br>  // Code that needs access to DI<br>});</pre><h3>Why Do We Need It?</h3><p>Angular’s DI system primarily works within specific contexts:</p><ul><li>Component constructors</li><li>Injectable service constructors</li><li>Lifecycle hooks</li><li>Template expressions</li></ul><p>But what about:</p><ul><li>Standalone functions</li><li>Observable streams</li><li>Event handlers</li><li>Promise callbacks</li><li>Third-party library integration</li></ul><p>In these cases, runInInjectionContext bridges the gap by providing temporary access to Angular&#39;s DI system.</p><h3>When to Use runInInjectionContext</h3><h4>1. Custom RxJS Operators</h4><p>When creating custom RxJS operators that need access to services:</p><pre>import { Injector, runInInjectionContext } from &#39;@angular/core&#39;;<br>import { Observable, map } from &#39;rxjs&#39;;<br>import { TranslateService } from &#39;./translate.service&#39;;<br><br>export function translateText&lt;T&gt;(injector: Injector, textSelector: (value: T) =&gt; string) {<br>  return (source: Observable&lt;T&gt;) =&gt; {<br>    return source.pipe(<br>      map(value =&gt; {<br>        return runInInjectionContext(injector, () =&gt; {<br>          // Access Angular DI inside this function<br>          const translateService = injector.get(TranslateService);<br>          const textToTranslate = textSelector(value);<br>          const translatedText = translateService.translate(textToTranslate);<br>          <br>          return {<br>            ...value,<br>            translatedText<br>          };<br>        });<br>      })<br>    );<br>  };<br>}<br><br>// Usage in component<br>@Component({...})<br>export class MyComponent {<br>  constructor(private injector: Injector) {}<br>  <br>  ngOnInit() {<br>    this.dataStream$.pipe(<br>      translateText(this.injector, item =&gt; item.description)<br>    ).subscribe(result =&gt; {<br>      console.log(result.translatedText);<br>    });<br>  }<br>}</pre><h4>2. Utility Functions</h4><p>When creating helper functions that require access to services:</p><pre>import { Injector, runInInjectionContext } from &#39;@angular/core&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br><br>export function navigateToItem(injector: Injector, itemId: string) {<br>  runInInjectionContext(injector, () =&gt; {<br>    const router = injector.get(Router);<br>    router.navigate([&#39;/items&#39;, itemId]);<br>  });<br>}</pre><h4>3. Callback Functions</h4><p>When dealing with callbacks from third-party libraries:</p><pre>import { Injector, runInInjectionContext } from &#39;@angular/core&#39;;<br>import { NotificationService } from &#39;./notification.service&#39;;<br><br>@Component({...})<br>export class FileUploadComponent {<br>  constructor(private injector: Injector) {}<br>  <br>  initializeUploader() {<br>    const uploader = new ThirdPartyUploader({<br>      onSuccess: (result) =&gt; {<br>        runInInjectionContext(this.injector, () =&gt; {<br>          const notificationService = this.injector.get(NotificationService);<br>          notificationService.showSuccess(&#39;File uploaded successfully!&#39;);<br>        });<br>      }<br>    });<br>  }<br>}</pre><h4>4. Integration with Web APIs</h4><p>When working with browser APIs that use callbacks:</p><pre>import { Injector, runInInjectionContext } from &#39;@angular/core&#39;;<br>import { LoggingService } from &#39;./logging.service&#39;;<br><br>@Component({...})<br>export class GeolocationComponent {<br>  constructor(private injector: Injector) {}<br>  <br>  getUserLocation() {<br>    navigator.geolocation.getCurrentPosition(<br>      (position) =&gt; {<br>        runInInjectionContext(this.injector, () =&gt; {<br>          const logger = this.injector.get(LoggingService);<br>          logger.logInfo(&#39;User location acquired&#39;);<br>          this.processLocation(position);<br>        });<br>      },<br>      (error) =&gt; {<br>        runInInjectionContext(this.injector, () =&gt; {<br>          const logger = this.injector.get(LoggingService);<br>          logger.logError(&#39;Failed to get location&#39;, error);<br>        });<br>      }<br>    );<br>  }<br>  <br>  private processLocation(position: GeolocationPosition) {<br>    // Process the position data<br>  }<br>}</pre><h3>Best Practices When Using runInInjectionContext</h3><ol><li><strong>Don’t Overuse It</strong>: If you find yourself using runInInjectionContext extensively, reconsider your architecture. It might indicate your code is not properly organized around Angular&#39;s component structure.</li><li><strong>Store the Injector</strong>: Keep a reference to the injector that will be used across multiple contexts:</li></ol><pre>@Component({...})<br>export class MyComponent implements OnInit {<br>  constructor(private injector: Injector) {}<br>  <br>  ngOnInit() {<br>    this.initializeThirdPartyLibrary();<br>  }<br>  <br>  private initializeThirdPartyLibrary() {<br>    const library = new ThirdPartyLibrary({<br>      onEvent: (data) =&gt; this.handleLibraryEvent(data)<br>    });<br>  }<br>  <br>  private handleLibraryEvent(data: any) {<br>    runInInjectionContext(this.injector, () =&gt; {<br>      // Access Angular DI here<br>    });<br>  }<br>}</pre><p>3.<strong> Consider Creating Service Methods</strong>: For frequently used operations, create service methods instead of standalone utility functions:</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class UtilityService {<br>  processData(data: any) {<br>    // Handle data processing with DI access<br>  }<br>}<br><br>// Then use it like this:<br>runInInjectionContext(injector, () =&gt; {<br>  const utilityService = injector.get(UtilityService);<br>  utilityService.processData(data);<br>});</pre><h3>A Complete Example: Form Validation</h3><p>Here’s a comprehensive example showing how to use runInInjectionContext with asynchronous form validation:</p><pre>import { AbstractControl, AsyncValidatorFn, ValidationErrors } from &#39;@angular/forms&#39;;<br>import { Injector, runInInjectionContext } from &#39;@angular/core&#39;;<br>import { Observable, of } from &#39;rxjs&#39;;<br>import { map, catchError, delay } from &#39;rxjs/operators&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>// Factory function that produces an async validator<br>export function createUsernameValidator(injector: Injector): AsyncValidatorFn {<br>  // Return the validator function<br>  return (control: AbstractControl): Observable&lt;ValidationErrors | null&gt; =&gt; {<br>    // If the control is empty, skip validation<br>    if (!control.value) {<br>      return of(null);<br>    }<br>    <br>    // Run in injection context to access services<br>    return runInInjectionContext(injector, () =&gt; {<br>      // Get the user service from the injector<br>      const userService = injector.get(UserService);<br>      <br>      // Call service method to check username availability<br>      return userService.checkUsernameAvailability(control.value).pipe(<br>        map(isAvailable =&gt; (isAvailable ? null : { usernameExists: true })),<br>        catchError(() =&gt; of({ serverError: true })),<br>        delay(500) // Add a small delay to prevent too many requests<br>      );<br>    });<br>  };<br>}<br><br>// Usage in a component<br>@Component({<br>  selector: &#39;app-registration&#39;,<br>  template: `<br>    &lt;form [formGroup]=&quot;registrationForm&quot;&gt;<br>      &lt;input formControlName=&quot;username&quot; placeholder=&quot;Username&quot;&gt;<br>      &lt;div *ngIf=&quot;username.pending&quot;&gt;Checking availability...&lt;/div&gt;<br>      &lt;div *ngIf=&quot;username.errors?.usernameExists&quot;&gt;Username already taken&lt;/div&gt;<br>      &lt;div *ngIf=&quot;username.errors?.serverError&quot;&gt;Server error, try again&lt;/div&gt;<br>    &lt;/form&gt;<br>  `<br>})<br>export class RegistrationComponent implements OnInit {<br>  registrationForm: FormGroup;<br>  <br>  constructor(<br>    private fb: FormBuilder, <br>    private injector: Injector<br>  ) {}<br>  <br>  ngOnInit() {<br>    this.registrationForm = this.fb.group({<br>      username: [&#39;&#39;, {<br>        validators: [Validators.required, Validators.minLength(3)],<br>        asyncValidators: [createUsernameValidator(this.injector)],<br>        updateOn: &#39;blur&#39;<br>      }]<br>    });<br>  }<br>  <br>  get username() {<br>    return this.registrationForm.get(&#39;username&#39;);<br>  }<br>}<br><br>// The user service implementation<br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class UserService {<br>  constructor(private http: HttpClient) {}<br>  <br>  checkUsernameAvailability(username: string): Observable&lt;boolean&gt; {<br>    return this.http.get&lt;boolean&gt;(`/api/check-username/${username}`);<br>  }<br>}</pre><h3>Conclusion</h3><p>runInInjectionContext is a powerful tool in Angular&#39;s toolbox that helps solve dependency injection challenges outside of typical Angular contexts. While it shouldn&#39;t be your first choice for accessing services, it provides a clean solution for specific scenarios like RxJS operators, utility functions, and third-party integration.</p><p>By understanding when and how to use this function appropriately, you can maintain clean architecture while still having the flexibility to access Angular’s dependency injection system when necessary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0328ea3e013f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tenantcloud-engineering/understanding-runininjectioncontext-in-angular-how-why-and-when-to-use-it-0328ea3e013f">Understanding runInInjectionContext in Angular: How, Why, and When to Use It</a> was originally published in <a href="https://medium.com/tenantcloud-engineering">tenantcloud-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dependency Injection in Angular: Constructor Injection vs.]]></title>
            <link>https://medium.com/tenantcloud-engineering/understanding-dependency-injection-in-angular-constructor-injection-vs-5c75f0226f70?source=rss-2197d367fb44------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c75f0226f70</guid>
            <dc:creator><![CDATA[Olia Pankiv]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 12:18:10 GMT</pubDate>
            <atom:updated>2025-05-15T09:19:29.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Dependency Injection in Angular: Constructor Injection vs. Inject Decorator vs. inject() Function</h3><p>Angular provides several methods for dependency injection: constructor injection, the @Inject decorator, and the newer inject() function. Each approach allows you to incorporate services and other dependencies into your components, but they serve different purposes and have distinct use cases.</p><h3>Constructor Injection</h3><p>Constructor injection is Angular’s recommended and most common approach for dependency injection. It leverages TypeScript’s type system to automatically inject services.</p><h4>How Constructor Injection Works</h4><pre>import { Component } from &#39;@angular/core&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  templateUrl: &#39;./user-list.component.html&#39;<br>})<br>export class UserListComponent {<br>  users: any[] = [];<br><br>  constructor(private userService: UserService) {<br>    this.users = this.userService.getUsers();<br>  }<br>}</pre><p>In this example, Angular’s dependency injection system:</p><ol><li>Recognizes that UserService is required</li><li>Locates or creates an instance of UserService from the injector hierarchy</li><li>Provides that instance when creating the component</li></ol><h4>Advantages of Constructor Injection</h4><ul><li><strong>Clean and readable</strong>: Dependencies are clearly visible in the constructor signature</li><li><strong>Type safety</strong>: TypeScript provides compile-time type checking</li><li><strong>Testability</strong>: Makes unit testing straightforward with mock services</li><li><strong>Follows best practices</strong>: Adheres to the principle of explicit dependencies</li></ul><h3>@Inject Decorator</h3><p>The @Inject decorator provides more control over injection in specific scenarios where constructor injection isn&#39;t sufficient.</p><h4>How @Inject Works</h4><pre>import { Component, Inject } from &#39;@angular/core&#39;;<br>import { USER_SERVICE_TOKEN } from &#39;./injection-tokens&#39;;<br><br>@Component({<br>  selector: &#39;app-profile&#39;,<br>  templateUrl: &#39;./profile.component.html&#39;<br>})<br>export class ProfileComponent {<br>  constructor(@Inject(USER_SERVICE_TOKEN) private userService: any) {<br>    // Use the injected service<br>  }<br>}</pre><h4>Using @Inject with Injection Tokens</h4><pre>// injection-tokens.ts<br>import { InjectionToken } from &#39;@angular/core&#39;;<br><br>export const API_URL = new InjectionToken&lt;string&gt;(&#39;api.url&#39;);<br>export const CONFIG = new InjectionToken&lt;any&gt;(&#39;app.config&#39;);</pre><pre>// app.module.ts<br>@NgModule({<br>  // ...<br>  providers: [<br>    { provide: API_URL, useValue: &#39;https://api.example.com&#39; },<br>    { provide: CONFIG, useValue: { timeout: 3000, retries: 3 } }<br>  ]<br>})<br>export class AppModule { }</pre><pre>// data.service.ts<br>import { Injectable, Inject } from &#39;@angular/core&#39;;<br>import { API_URL, CONFIG } from &#39;./injection-tokens&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class DataService {<br>  constructor(<br>    @Inject(API_URL) private apiUrl: string,<br>    @Inject(CONFIG) private config: any<br>  ) {<br>    console.log(`Using API at ${apiUrl} with timeout ${config.timeout}ms`);<br>  }<br>}</pre><h4>When to Use @Inject</h4><ol><li><strong>Non-class dependencies</strong>: Injecting primitive values, objects, or custom tokens</li><li><strong>Named dependencies</strong>: When you need multiple instances of the same type</li><li><strong>Optional dependencies</strong>: Combined with @Optional() for dependencies that might not exist</li><li><strong>Forward references</strong>: Handling circular dependencies</li><li><strong>Custom providers</strong>: Working with useFactory, useValue, or useExisting</li></ol><h3>The inject() Function</h3><p>The inject() function is a newer approach introduced in Angular 14+ that provides a functional way to inject dependencies outside of constructors.</p><h4>How inject() Works</h4><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Component({<br>  selector: &#39;app-user-dashboard&#39;,<br>  templateUrl: &#39;./user-dashboard.component.html&#39;<br>})<br>export class UserDashboardComponent {<br>  private userService = inject(UserService);<br>  users = this.userService.getUsers();<br>}</pre><h4>Key Features of inject()</h4><ul><li><strong>Functional approach</strong>: Injects dependencies directly in the class body</li><li><strong>Works in field initialization</strong>: Can be used to initialize class fields</li><li><strong>Supports injection tokens</strong>: Works with InjectionTokens just like @Inject</li><li><strong>Available in various contexts</strong>: Works in components, services, directives, pipes, and more</li></ul><h4>When to Use inject()</h4><ol><li><strong>Standalone components</strong>: Particularly useful with Angular’s standalone components</li><li><strong>Composition patterns</strong>: When implementing composition over inheritance</li><li><strong>Cleaner service access</strong>: To avoid long constructor parameter lists</li><li><strong>Lazy injection</strong>: When you need to conditionally inject dependencies</li><li><strong>Simpler initialization</strong>: For cleaner initialization of class fields</li></ol><h4>Advanced inject() Usage</h4><p><strong>With injection tokens:</strong></p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { API_URL, CONFIG } from &#39;./injection-tokens&#39;;<br><br>@Component({<br>  selector: &#39;app-settings&#39;,<br>  templateUrl: &#39;./settings.component.html&#39;<br>})<br>export class SettingsComponent {<br>  private apiUrl = inject(API_URL);<br>  private config = inject(CONFIG);<br>  <br>  timeout = this.config.timeout;<br>  endpoint = this.apiUrl;<br>}</pre><p><strong>Optional dependencies:</strong></p><pre>import { Component, inject, Optional } from &#39;@angular/core&#39;;<br>import { AnalyticsService } from &#39;./analytics.service&#39;;<br><br>@Component({<br>  selector: &#39;app-feature&#39;,<br>  template: &#39;...&#39;<br>})<br>export class FeatureComponent {<br>  // Will be null if AnalyticsService is not provided<br>  private analytics = inject(AnalyticsService, { optional: true });<br>  <br>  logFeatureUse(): void {<br>    if (this.analytics) {<br>      this.analytics.trackEvent(&#39;feature_used&#39;);<br>    }<br>  }<br>}</pre><p><strong>Environment-specific injection:</strong></p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { LoggerService } from &#39;./logger.service&#39;;<br>import { environment } from &#39;../environments/environment&#39;;<br><br>@Component({<br>  selector: &#39;app-debug&#39;,<br>  templateUrl: &#39;./debug.component.html&#39;<br>})<br>export class DebugComponent {<br>  private logger = environment.production ? <br>    inject(ProductionLoggerService) : <br>    inject(DevelopmentLoggerService);<br>    <br>  logDebugInfo(): void {<br>    this.logger.log(&#39;Debug info&#39;);<br>  }<br>}</pre><h3>Practical Examples Comparing All Approaches</h3><h4>Example 1: Basic Service Injection</h4><p><strong>Constructor Injection:</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { LoggerService } from &#39;./logger.service&#39;;<br><br>@Component({<br>  selector: &#39;app-dashboard&#39;,<br>  template: &#39;&lt;div&gt;Dashboard&lt;/div&gt;&#39;<br>})<br>export class DashboardComponent {<br>  constructor(private logger: LoggerService) {<br>    this.logger.log(&#39;Dashboard component initialized&#39;);<br>  }<br>}</pre><p><strong>Inject Decorator:</strong></p><pre>import { Component, Inject } from &#39;@angular/core&#39;;<br>import { LoggerService } from &#39;./logger.service&#39;;<br><br>@Component({<br>  selector: &#39;app-dashboard&#39;,<br>  template: &#39;&lt;div&gt;Dashboard&lt;/div&gt;&#39;<br>})<br>export class DashboardComponent {<br>  constructor(@Inject(LoggerService) private logger: LoggerService) {<br>    this.logger.log(&#39;Dashboard component initialized&#39;);<br>  }<br>}</pre><p><strong>inject() Function:</strong></p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { LoggerService } from &#39;./logger.service&#39;;<br><br>@Component({<br>  selector: &#39;app-dashboard&#39;,<br>  template: &#39;&lt;div&gt;Dashboard&lt;/div&gt;&#39;<br>})<br>export class DashboardComponent {<br>  private logger = inject(LoggerService);<br>  <br>  ngOnInit() {<br>    this.logger.log(&#39;Dashboard component initialized&#39;);<br>  }<br>}</pre><h4>Example 2: Working with Configuration Values</h4><p><strong>Using @Inject for Configuration:</strong></p><pre>// Define token<br>export const APP_CONFIG = new InjectionToken&lt;AppConfig&gt;(&#39;app.config&#39;);<br><br>// Provide configuration<br>@NgModule({<br>  providers: [<br>    { <br>      provide: APP_CONFIG, <br>      useValue: { <br>        apiEndpoint: &#39;https://api.example.com&#39;,<br>        theme: &#39;dark&#39;,<br>        cacheTimeout: 60000<br>      } <br>    }<br>  ]<br>})<br>export class AppModule { }<br><br>// Inject configuration<br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;<br>})<br>export class AppComponent {<br>  constructor(@Inject(APP_CONFIG) private config: AppConfig) {<br>    console.log(`Using API: ${config.apiEndpoint} with ${config.theme} theme`);<br>  }<br>}</pre><p><strong>Using inject() for Configuration:</strong></p><pre>// Same token and provider setup<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;<br>})<br>export class AppComponent {<br>  private config = inject(APP_CONFIG);<br>  theme = this.config.theme;<br>  <br>  ngOnInit() {<br>    console.log(`Using API: ${this.config.apiEndpoint} with ${this.theme} theme`);<br>  }<br>}</pre><h4>Example 3: Combining Multiple Services</h4><p><strong>Constructor Injection (gets verbose):</strong></p><pre>@Component({<br>  selector: &#39;app-complex&#39;,<br>  templateUrl: &#39;./complex.component.html&#39;<br>})<br>export class ComplexComponent {<br>  constructor(<br>    private userService: UserService,<br>    private authService: AuthService,<br>    private loggerService: LoggerService,<br>    private analyticsService: AnalyticsService,<br>    private translationService: TranslationService<br>  ) {<br>    // Lots of initialization code<br>  }<br>}</pre><p><strong>Using inject() (cleaner):</strong></p><pre>@Component({<br>  selector: &#39;app-complex&#39;,<br>  templateUrl: &#39;./complex.component.html&#39;<br>})<br>export class ComplexComponent {<br>  private userService = inject(UserService);<br>  private authService = inject(AuthService);<br>  private logger = inject(LoggerService);<br>  private analytics = inject(AnalyticsService);<br>  private translation = inject(TranslationService);<br>  <br>  // Constructor is now clean<br>  constructor() {<br>    this.setupServices();<br>  }<br>  <br>  private setupServices(): void {<br>    // Initialization code<br>  }<br>}</pre><h3>When to Use Each Approach</h3><h4>Constructor Injection</h4><ul><li><strong>Use when</strong>: You need clear dependency documentation, working with traditional components, testing with mocks</li><li><strong>Advantages</strong>: Explicit dependencies, works with TypeScript’s type system, familiar pattern</li><li><strong>Disadvantages</strong>: Can get verbose with many dependencies</li></ul><h4>@Inject Decorator</h4><ul><li><strong>Use when</strong>: Working with custom tokens, primitive values, or when you need more control over injection</li><li><strong>Advantages</strong>: Precise control over injection, works well with tokens and non-class dependencies</li><li><strong>Disadvantages</strong>: More verbose than constructor injection for standard services</li></ul><h4>inject() Function</h4><ul><li><strong>Use when</strong>: Working with standalone components, need cleaner field initialization, or want to avoid constructor bloat</li><li><strong>Advantages</strong>: Cleaner syntax, works outside constructors, supports conditional injection</li><li><strong>Disadvantages</strong>: Newer API (requires Angular 14+), can make dependencies less explicit</li></ul><h3>Best Practices</h3><ol><li><strong>Be consistent</strong> within your codebase to maintain readability</li><li><strong>Consider performance</strong>: inject() can help reduce boilerplate but doesn’t change the underlying injection mechanics</li><li><strong>Choose appropriately</strong>:</li></ol><ul><li>Constructor injection for most class-based dependencies and testability</li><li>@Inject for tokens and special injection scenarios</li><li>inject() for cleaner component code and standalone components</li></ul><p>4. <strong>Testing considerations</strong>:</p><ul><li>Constructor injection makes traditional unit testing simpler</li><li>inject() requires special test setup with TestBed</li></ul><p>By understanding the strengths and appropriate use cases for constructor injection, the @Inject decorator, and the inject() function, you can build more maintainable Angular applications with clean, flexible dependency management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c75f0226f70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tenantcloud-engineering/understanding-dependency-injection-in-angular-constructor-injection-vs-5c75f0226f70">Understanding Dependency Injection in Angular: Constructor Injection vs.</a> was originally published in <a href="https://medium.com/tenantcloud-engineering">tenantcloud-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ViewProviders vs Providers in Angular]]></title>
            <link>https://medium.com/tenantcloud-engineering/understanding-viewproviders-vs-providers-in-angular-4d7a7ef1607b?source=rss-2197d367fb44------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d7a7ef1607b</guid>
            <dc:creator><![CDATA[Olia Pankiv]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 11:53:16 GMT</pubDate>
            <atom:updated>2025-05-25T13:03:39.151Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular’s dependency injection system is one of its most powerful features, allowing for clean separation of concerns and efficient code organization. At the heart of this system are two important configuration options: providers and viewProviders. While they may appear similar at first glance, they serve different purposes and understanding their nuances can significantly improve your component architecture.</p><h3><strong>Basic Concepts</strong></h3><h4><strong>Providers</strong></h4><p>The providers array in a component&#39;s decorator makes services available to:</p><ul><li>The component itself</li><li>The component’s template</li><li>All child components and their templates</li><li>Any content projected into the component (ng-content)</li></ul><h4>ViewProviders</h4><p>The viewProviders array makes services available to:</p><ul><li>The component itself</li><li>The component’s template</li><li>All child components and their templates</li><li>But NOT to content projected into the component via ng-content</li></ul><h3>The Key Difference</h3><p>The primary distinction lies in how Angular treats <strong>content children</strong> versus <strong>view children</strong>:</p><ul><li><strong>View children</strong>: Elements created by the component’s template</li><li><strong>Content children</strong>: Elements projected into the component via &lt;ng-content&gt;</li></ul><p>Using viewProviders creates a &quot;privacy boundary&quot; that prevents projected content from accessing those services.</p><h3>Visual Representation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fD_5MlRDmPHBxRPv_ZfwPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIAHV6E4tHWvTLrNj11OUg.png" /></figure><h3>Practical Examples</h3><h4>Example 1: Using providers</h4><pre>// data.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class DataService {<br> private data = &#39;Original data from service&#39;;<br><br> getData(): string {<br>  return this.data;<br> }<br>}</pre><pre>// app.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;app-parent&gt;<br>      &lt;app-content&gt;&lt;/app-content&gt;<br>    &lt;/app-parent&gt;<br>  `,<br>  styleUrl: &#39;./app.component.scss&#39;<br>})<br>export class AppComponent {}</pre><pre>// parent.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;Parent Component&lt;/h2&gt;<br>      &lt;p&gt;Parent Data: {{ dataService.getData() }}&lt;/p&gt;<br>      <br>      &lt;app-child&gt;&lt;/app-child&gt;<br><br>      &lt;ng-content&gt;&lt;/ng-content&gt;<br>    &lt;/div&gt;<br>  `,<br>  providers: [<br>    { provide: DataService, useValue: { getData: () =&gt; &#39;Parent provider data&#39; } }<br>  ]<br>})<br>export class ParentComponent {<br>  constructor(public dataService: DataService) {}<br>}</pre><pre>// child.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-child&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h3&gt;Child Component&lt;/h3&gt;<br>      &lt;p&gt;Child Data: {{ dataService.getData() }}&lt;/p&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class ChildComponent {<br>  constructor(public dataService: DataService) {}<br>}</pre><pre>// content.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-content&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h4&gt;Content Child Component&lt;/h4&gt;<br>      &lt;p&gt;Content Child Data: {{ dataService.getData() }}&lt;/p&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class ContentComponent {<br>  constructor(public dataService: DataService) {}<br>}</pre><p><strong>Result with providers:</strong></p><ul><li>Parent Component: “Parent provider data”</li><li>Child Component: “Parent provider data” (inherited from parent)</li><li>Content Component: “Parent provider data” (inherited from parent)</li></ul><h4>Example 2: Using viewProviders</h4><p>If we change the parent component to use viewProviders instead:</p><pre>// parent.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;h2&gt;Parent Component&lt;/h2&gt;<br>      &lt;p&gt;Parent Data: {{ dataService.getData() }}&lt;/p&gt;<br>      <br>      &lt;app-child&gt;&lt;/app-child&gt;<br><br>      &lt;ng-content&gt;&lt;/ng-content&gt;<br>    &lt;/div&gt;<br>  `,<br>  viewProviders: [<br>    { provide: DataService, useValue: { getData: () =&gt; &#39;Parent provider data&#39; } }<br>  ]<br>})<br>export class ParentComponent {<br>  constructor(public dataService: DataService) {}<br>}</pre><p><strong>Result with viewProviders:</strong></p><ul><li>Parent Component: “Parent viewProvider data”</li><li>Child Component: “Parent viewProvider data” (inherited from parent)</li><li>Content Component: “Original data from service” (NOT inherited from parent)</li></ul><h4>Example 3: Both providers and viewProviders</h4><pre>// parent.component.ts (with both)<br>import { Component } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: `<br>   &lt;div&gt;<br>      &lt;h2&gt;Parent Component&lt;/h2&gt;<br>      &lt;p&gt;Parent Data: {{ dataService.getData() }}&lt;/p&gt;<br>      <br>      &lt;app-child&gt;&lt;/app-child&gt;<br><br>      &lt;ng-content&gt;&lt;/ng-content&gt;<br>    &lt;/div&gt;<br>  `,<br>  providers: [<br>    { provide: DataService, useValue: { getData: () =&gt; &#39;Parent provider data&#39; } }<br>  ],<br>  viewProviders: [<br>    { provide: DataService, useValue: { getData: () =&gt; &#39;Parent viewProvider data&#39; } }<br>  ]<br>})<br>export class ParentComponent {<br>  constructor(public dataService: DataService) {}<br>}</pre><p><strong>Result:</strong></p><ul><li>Parent Component: “Parent viewProvider data” (viewProviders take precedence for the component itself)</li><li>Child Component: “Parent viewProvider data” (inherited from parent’s viewProviders)</li><li>Content Child Component: “Parent provider data” (inherited from parent’s providers)</li></ul><h3>When to Use Which?</h3><h4>Use providers when:</h4><ul><li>You want both view children and content children to access the same service instance</li><li>You’re creating reusable components that may include projected content</li><li>You need to provide services to your entire component subtree</li></ul><h4>Use viewProviders when:</h4><ul><li>You want to create a “private” service instance that content children can’t access</li><li>You want to prevent name collisions when content projects from different sources</li><li>You want to enforce stronger encapsulation between your component and projected content</li></ul><h3>Real-World Use Cases</h3><h4>1. Form Components</h4><p>When building form components that might include projected content (like custom form controls), using viewProviders can prevent conflicts between the form handling services used by your component and any form logic that might exist in projected content.</p><h4>2. Component Libraries</h4><p>When creating a component library, using viewProviders helps ensure that internal implementation details don&#39;t leak into applications using your library, creating a cleaner public API.</p><h4>3. Feature Modules</h4><p>In complex applications with feature modules, carefully choosing between providers and viewProviders can help manage service scope and prevent unwanted service sharing between independent features.</p><h3>Conclusion</h3><p>Understanding the difference between providers and viewProviders gives you finer control over Angular&#39;s dependency injection system. This knowledge helps create more maintainable, encapsulated components while reducing unexpected behaviors due to service instance sharing.</p><p>By choosing the appropriate provider mechanism, you can control precisely how services are shared throughout your component hierarchy, leading to more predictable and maintainable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d7a7ef1607b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tenantcloud-engineering/understanding-viewproviders-vs-providers-in-angular-4d7a7ef1607b">Understanding ViewProviders vs Providers in Angular</a> was originally published in <a href="https://medium.com/tenantcloud-engineering">tenantcloud-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>