DEV Community

Cover image for Functional Programming in Angular: Exploring inject and Resources
Daniel Sogl
Daniel Sogl

Posted on • Originally published at Medium

Functional Programming in Angular: Exploring inject and Resources

Angular’s evolving ecosystem is shifting toward a more functional and reactive programming paradigm. With tools like Signals, the Resource API, and the inject function, developers can simplify application logic, reduce boilerplate, and enhance reusability.

This blog post explores how Angular’s modern features empower developers to handle asynchronous logic in a clean, declarative, and reactive way.

Key Benefits of Angular’s Functional Features

  1. Reusable Functions with Dependency Injection: The inject function allows developers to create standalone functions that seamlessly integrate with Angular's dependency injection system. This decouples business logic from components and services, making functions reusable across the application.
  2. Simplified State Management: Automatically handle loading, success, and error states.
  3. Enhanced Reactivity: Automatically update data when dependencies change.
  4. Reduced Boilerplate: Focus on the logic, not manual subscriptions or lifecycle management.
  5. Improved Readability: Declarative templates make UI state transitions easy to understand.

Step 1: The API and Data Model

For this example, we’ll fetch posts from a REST API. Each post has the following structure:

export interface Post {
  userId: number;
  id: number;
  title: "string;"
  body: string;
}
Enter fullscreen mode Exit fullscreen mode

The base URL for the API is provided via an InjectionToken:

import { InjectionToken } from '@angular/core';

export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL', {
  providedIn: 'root',
  factory: () => 'https://jsonplaceholder.typicode.com',
});
Enter fullscreen mode Exit fullscreen mode

Step 2: Define Data Fetching Functions

1. Traditional RxJS-Based Approach

The following function fetches a post by its ID using Angular’s HttpClient:

import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core';
import { Observable } from 'rxjs';
import { API_BASE_URL } from '../tokens/base-url.token';
import { Post } from './post.model';

export function getPostById(postId: number): Observable<Post> {
  const http = inject(HttpClient);
  const baseUrl = inject(API_BASE_URL);

  return http.get<Post>(`${baseUrl}/posts/${postId}`);
}
Enter fullscreen mode Exit fullscreen mode

To use this function in a component, you can bind it to an observable and display the result with the async pipe:

import { AsyncPipe, JsonPipe } from '@angular/common';
import { Component, signal } from '@angular/core';
import { getPostById } from './shared/posts.inject';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [AsyncPipe, JsonPipe],
  template: `
    @if (post$ | async; as post) {
      <p>{{ post | json }}</p>
    } @else {
      <p>Loading...</p>
    }
  `,
})
export class AppComponent {
  private readonly postId = signal(1);

  protected readonly post$ = getPostById(this.postId());
}
Enter fullscreen mode Exit fullscreen mode

Limitations

  • Reactivity Issues: Signal changes (e.g., postId) don’t automatically trigger a new fetch.
  • Manual Error Handling: You must write custom logic for loading and error states.

2. Signal-Based Resource API Approach

The Resource API simplifies reactivity and state management. Here’s a function that uses the Resource API:

import { inject, resource, ResourceRef, Signal } from '@angular/core';
import { API_BASE_URL } from '../tokens/base-url.token';

export function getPostByIdResource(postId: Signal<number>): ResourceRef<Post> {
  const baseUrl = inject(API_BASE_URL);
  return resource<Post, { id: number }>({
    request: () => ({ id: postId() }),
    loader: async ({ request, abortSignal }) => {
      const response = await fetch(`${baseUrl}/posts/${request.id}`, {
        signal: abortSignal,
      });
      return response.json();
    },
  });
}
Enter fullscreen mode Exit fullscreen mode

This approach:

  • Automatically reloads data when postId changes.
  • Handles loading, error, and success states declaratively.

In a component:

import { JsonPipe } from '@angular/common';
import { Component, signal } from '@angular/core';
import { getPostByIdResource } from './shared/posts.inject';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [JsonPipe],
  template: `
    @if (post.isLoading()) {
      <p>Loading...</p>
    } @else if (post.error()) {
      <p>Error: {{ post.error() }}</p>
    } @else {
      <p>{{ post.value() | json }}</p>
    }
  `,
})
export class AppComponent {
  private readonly postId = signal(1);

  protected readonly post = getPostByIdResource(this.postId);
}
Enter fullscreen mode Exit fullscreen mode

Key Features of the Resource API

Declarative State Management

The Resource API automatically manages states like loading, error, and success. This removes the need for custom flags and ensures cleaner templates.

Reactivity

The Resource API is tightly integrated with Signals. Changes to a Signal automatically trigger the loader function, ensuring that your UI always reflects the latest data.

Error Handling

Errors are centralized and exposed via .error(), simplifying error management in templates.

Automatic Lifecycle Management

The API cancels ongoing requests when dependencies (e.g., postId) change, preventing race conditions and stale data.


RxJS vs Resource API: A Quick Comparison

Feature RxJS (Observable) Resource API (Signal)
State Management Manual Automatic (loading, error)
Reactivity Requires custom setup Built-in
Error Handling Manual Declarative
Lifecycle Handling Requires cleanup Automatic

Conclusion

Angular’s inject function and Signal-based Resource API represent a leap forward in simplifying asynchronous logic. With these tools, developers can:

  1. Decouple business logic from components.
  2. Write reusable functions that integrate seamlessly with Angular’s dependency injection system.
  3. Eliminate boilerplate for state management.
  4. Build reactive and declarative applications with ease.

The Resource API, in particular, is ideal for modern Angular projects, providing automatic reactivity and declarative state handling. Start exploring these features today and take your Angular development to the next level!

Top comments (0)