DEV Community

Tomasz Flis
Tomasz Flis

Posted on


Angular code simplicity with inject

The feature

The angular team in version 14 introduced the inject method to play with dependency injection without needing to add a constructor. Here is an example of a dummy service that is injected:

import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";

@Injectable({ providedIn: 'root' })
export class ApiService {
    list$(): Observable<any> {
        return of([1,2,3]);
Enter fullscreen mode Exit fullscreen mode

Furthermore, the example used in the component would be:

import { Component, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from './api.service';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  standalone: true
export class AppComponent {
  title = 'simple-injection';

  private readonly apiService = inject(ApiService);

  getList$(): Observable<any> {
    return this.apiService.list$();
Enter fullscreen mode Exit fullscreen mode

No need to use a constructor, which is fantastic and provides cleaner code.

The util approach

There could be situations the method is more extensive and more complicated. We can introduce the util approach by using the inject method once again. All we have to do is to extract the method to separate functions or even files and use the inject method there:

function getList$(): Observable<any> {
  return inject(ApiService).list$().pipe(
    map(data => data.list)
Enter fullscreen mode Exit fullscreen mode

And then at the component level:

list$ = getList$();
Enter fullscreen mode Exit fullscreen mode

We have to remember that the inject method can be used only in two situations:

  1. in a constructor, a constructor parameter and a field initializer (like above)
  2. factory provider:
providers: [
  {provide: User, useFactory: () => {
    const posts = inject(Posts);
    return new User(posts);
Enter fullscreen mode Exit fullscreen mode


The inject method is a compelling feature and can save a lot of code and introduce resuable parts of logic.

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!