Thanks to visit codestin.com
Credit goes to github.com

Skip to content

docs: update di guide (part 1) #62127

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

bencodezen
Copy link
Contributor

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • angular.dev application / infrastructure changes
  • Other... Please describe:

What is the current behavior?

The current dependency injection guide is fragmented and disconnected.

What is the new behavior?

This PR introduces the first iteration of changes to make the DI guide cohesive and up to date.

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

@bencodezen bencodezen requested review from jelbourn and JeanMeche June 18, 2025 18:56
@angular-robot angular-robot bot added the area: docs Related to the documentation label Jun 18, 2025
@ngbot ngbot bot added this to the Backlog milestone Jun 18, 2025
@bencodezen bencodezen added the action: review The PR is still awaiting reviews from at least one requested reviewer label Jun 18, 2025
Comment on lines +44 to +47
@Injectable({
providedIn: 'root'
})
```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should mention that providing this way enabled also tree shaking of the service (or lazy loading) if it's only used in lazy-loaded routes/deferred components.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JeanMeche Would it be accurate to update the intro to say:

When you create a service, you need to provide a configuration object that defines the scope for the service through the providedIn key. This enables Angular to tree-shake the service when it's used in lazy-loaded routes or deferred components.

@bencodezen bencodezen requested a review from alxhub June 18, 2025 19:00
@jelbourn jelbourn added adev: preview target: patch This PR is targeted for the next patch release labels Jun 18, 2025
Copy link

github-actions bot commented Jun 18, 2025

Deployed adev-preview for 399bd4d to: https://ng-dev-previews-fw--pr-angular-angular-62127-adev-prev-wy6p8srf.web.app

Note: As new commits are pushed to this pull request, this link is updated after the preview is rebuilt.

docs: use more accurate word choice

Co-authored-by: Matthieu Riegler <[email protected]>

docs: use better file name for example

Co-authored-by: Enea Jahollari <[email protected]>

docs: update dedicated di guide with more accurate statements
@bencodezen bencodezen force-pushed the docs/di-guide-pt-1 branch from 7d3da32 to 399bd4d Compare June 19, 2025 16:05
Comment on lines +18 to +25
Angular has a built-in dependency injection (DI) system that is designed to be powerful and flexible. It is built upon five core concepts:

- [Services](#services)
- [Dependencies](#dependencies)
- [Providers vs Consumers](#providers-vs-consumers)
- [Injectors](#injectors)
- [`inject()`](#inject)
- [Tokens](#tokens)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trying to think this through how I might frame this...

What do you think of organizing it like:

## How does dependency injection work in Angular?

There are two ways that code interacts with any dependency injection system:
* Code can *provide*, or makes available, values.
* Code can *inject*, or ask for, those values as dependencies.

"Values", in this context, can be any any JavaScript value, including objects and functions.

Angular components and directives automatically participate in DI, meaning that they can inject dependencies _and_ they are available to be injected.

From there, going into "Services" as the most common way of declaring some functionality can can be injected as a dependency, then injecting dependencies, then the full details on providers.

Tokens and injectors IMO can be their own sections later on and don't need to be considered one of the "main concepts", since these are somewhat more intermediate concepts that people don't need to know about right away. I know the outline had a "terminology" section here, but coming back to it now, I think we can drop that.

Comment on lines +29 to +31
A service is a JavaScript class in Angular that is typically used to share data or functionality across components, handle business logic, or interact with backend services.

All services use the `@Injectable()` decorator to distinguish itself from other JavaScript classes.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
A service is a JavaScript class in Angular that is typically used to share data or functionality across components, handle business logic, or interact with backend services.
All services use the `@Injectable()` decorator to distinguish itself from other JavaScript classes.
An Angular *service* is a TypeScript class decorated with `@Injectable`, which makes an instance of the class available via injection. You can use services to share data and functionality across your application.


```ts
@Injectable({ providedIn: 'root' })
export class AnalyticService {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
export class AnalyticService {
export class AnalyticsLogger {


All services use the `@Injectable()` decorator to distinguish itself from other JavaScript classes.

Here is a simplified example of what an analytics service that tracks event information could look like:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Here is a simplified example of what an analytics service that tracks event information could look like:
The following example declares a service named `AnalyticsLogger`:

Here is a simplified example of what an analytics service that tracks event information could look like:

```ts
@Injectable({ providedIn: 'root' })
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add at least a sentence after the examples about the providedIn: 'root'), even if it's something like

"The `providedIn: 'root'` option controls where this service is available for injection. See [Providing values for injection]() for details.

Comment on lines +12 to +14
1. **Improved code maintainability**: Dependency injection allows cleaner separation of concerns which enables easier refactoring and reducing code duplication.
2. **Scalability**: Modular functionality can be reused across multiple contexts and allows for easier scaling.
3. **Better testing**: DI allows unit tests to inject mock dependencies which can improve performance and make test coverage more comprehensive since things can be tested independently.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
1. **Improved code maintainability**: Dependency injection allows cleaner separation of concerns which enables easier refactoring and reducing code duplication.
2. **Scalability**: Modular functionality can be reused across multiple contexts and allows for easier scaling.
3. **Better testing**: DI allows unit tests to inject mock dependencies which can improve performance and make test coverage more comprehensive since things can be tested independently.
*. **Improved code maintainability**: Dependency injection allows cleaner separation of concerns which enables easier refactoring and reducing code duplication.
*. **Scalability**: Modular functionality can be reused across multiple contexts and allows for easier scaling.
*. **Better testing**: DI allows unit tests to easily use [test doubles](https://en.wikipedia.org/wiki/Test_double) for situations when using a real implementation is not practical.

})
}
}
```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be useful to have a subsection here like "Common types of services" and list maybe three to five examples people commonly use services, e.g.

* *Data clients:* abstract the details of making requests to a server for data retrieval and mutation
* *State Management:* defining state shared across multiple components or pages
* *Logging and Error Handling:* making a common API for logging or communicating error states to the user.
* *Event handling and dispatch:* code related to handling events or notifications that are not associated with a specific component, or for dispatching events and notifications to components, following the [observer pattern](https://en.wikipedia.org/wiki/Observer_pattern).

(feel free to tweak these examples, this is just a first pass)

- **State stores**: Shared data stores that help maintain application state
- **Factories**: Functions that create objects or values based on runtime conditions

### Providers vs Consumers
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think of, instead of having this "Providers vs Consumers" sections, organizing the topic such that we immediately go into "Injecting dependencies", which would cover the inject function as mechanism by which you retrieve dependencies. i.e., I wouldn't present inject as its own concept, it's just the way you inject things


#### `inject()`

The `inject()` is a built-in service provided by Angular that enables you to interface directly with Angular's injector system. It's a helper function that asks the Angular, "Can you get me this dependency?"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inject isn't a service, it's just a function.

I think the framing here could be something like

## Injecting dependencies
You can inject dependencies using Angular's `inject` in the constructor of components, directives, pipes, and services.

<example here>

You can only use the `inject` function in an _injection context_.

<something about injection contexts here>

The gist for injection contexts is that it's a part of Angular's lifecycle when you can use the inject function because there's an implicit Injector. We can probably want to just point to a more intermediate/advanced section from here; the the most part, people only need to care that you can call inject in the constructor of components, directives, services, and pipes.

@@ -1,29 +1,141 @@
<docs-decorative-header title="Dependency injection in Angular" imgSrc="adev/src/assets/images/dependency_injection.svg"> <!-- markdownlint-disable-line -->
"DI" is a design pattern and mechanism for creating and delivering some parts of an app to other parts of an app that require them.

Dependency Injection (DI) is a design pattern used to organize and share code across an application.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Dependency Injection (DI) is a design pattern used to organize and share code across an application.
[Dependency Injection (DI)](https://en.wikipedia.org/wiki/Dependency_injection) is a design pattern used to organize and share code across an application.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
action: review The PR is still awaiting reviews from at least one requested reviewer adev: preview area: docs Related to the documentation target: patch This PR is targeted for the next patch release
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants