You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Services are reusable pieces of code that can be shared across your Angular application. They typically handle data fetching, business logic, or other functionality that multiple components need to access.
4
+
5
+
## Creating a service
6
+
7
+
You can create a service with the [Angular CLI](tools/cli) with the following command:
8
+
9
+
```bash
10
+
ng generate service CUSTOM_NAME
11
+
```
12
+
13
+
This creates a dedicated `CUSTOM_NAME.ts` file in your `src` directory.
14
+
15
+
You can also manually create a service by adding the `@Injectable()` decorator to a TypeScript class. This tells Angular that the service can be injected as a dependency.
16
+
17
+
Here is an example of a service that allows users to add and request data:
18
+
19
+
```ts
20
+
// 📄 src/app/basic-data-store.ts
21
+
import { Injectable } from'@angular/core';
22
+
23
+
@Injectable({ providedIn: 'root' })
24
+
exportclassBasicDataStore {
25
+
private data:string[] = []
26
+
27
+
addData(item:string):void {
28
+
this.data.push(item)
29
+
}
30
+
31
+
getData():string[] {
32
+
return [...this.data]
33
+
}
34
+
}
35
+
```
36
+
37
+
## How services become available
38
+
39
+
When you use `@Injectable({ providedIn: 'root' })` in your service, Angular:
40
+
41
+
-**Creates a single instance** (singleton) for your entire application
42
+
-**Makes it available everywhere** without any additional configuration
43
+
-**Enables tree-shaking** so the service is only included in your JavaScript bundle if it's actually used
44
+
45
+
This is the recommended approach for most services.
46
+
47
+
## Injecting a service
48
+
49
+
Once you've created a service with `providedIn: 'root'`, you can inject it anywhere in your application using the `inject()` function from `@angular/core`.
50
+
51
+
### Injecting into a component
52
+
53
+
```angular-ts
54
+
import { Component, inject } from '@angular/core';
55
+
import { BasicDataStore } from './basic-data-store';
Copy file name to clipboardExpand all lines: adev-es/src/content/guide/di/creating-and-using-services.md
+24-24Lines changed: 24 additions & 24 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,20 +1,20 @@
1
-
# Creating and using services
1
+
# Creando y usando servicios
2
2
3
-
Services are reusable pieces of code that can be shared across your Angular application. They typically handle data fetching, business logic, or other functionality that multiple components need to access.
3
+
Los servicios son piezas de código reutilizables que pueden compartirse a través de tu aplicación Angular. Típicamente manejan la obtención de datos, lógica de negocio u otra funcionalidad que múltiples componentes necesitan acceder.
4
4
5
-
## Creating a service
5
+
## Creando un servicio
6
6
7
-
You can create a service with the [Angular CLI](tools/cli)with the following command:
7
+
Puedes crear un servicio con el [Angular CLI](tools/cli)con el siguiente comando:
8
8
9
9
```bash
10
10
ng generate service CUSTOM_NAME
11
11
```
12
12
13
-
This creates a dedicated `CUSTOM_NAME.ts`file in your`src` directory.
13
+
Esto crea un archivo dedicado `CUSTOM_NAME.ts`en tu directorio`src`.
14
14
15
-
You can also manually create a service by adding the `@Injectable()`decorator to a TypeScript class. This tells Angular that the service can be injected as a dependency.
15
+
También puedes crear manualmente un servicio añadiendo el decorador `@Injectable()`a una clase TypeScript. Esto le indica a Angular que el servicio puede ser inyectado como una dependencia.
16
16
17
-
Here is an example of a service that allows users to add and request data:
17
+
Aquí hay un ejemplo de un servicio que permite a los usuarios agregar y solicitar datos:
18
18
19
19
```ts
20
20
// 📄 src/app/basic-data-store.ts
@@ -34,21 +34,21 @@ export class BasicDataStore {
34
34
}
35
35
```
36
36
37
-
## How services become available
37
+
## Cómo los servicios se vuelven disponibles
38
38
39
-
When you use `@Injectable({ providedIn: 'root' })`in your service, Angular:
39
+
Cuando usas `@Injectable({ providedIn: 'root' })`en tu servicio, Angular:
40
40
41
-
-**Creates a single instance** (singleton) for your entire application
42
-
-**Makes it available everywhere**without any additional configuration
43
-
-**Enables tree-shaking**so the service is only included in your JavaScript bundle if it's actually used
41
+
-**Crea una única instancia** (singleton) para toda tu aplicación
42
+
-**Lo hace disponible en todas partes**sin ninguna configuración adicional
43
+
-**Habilita tree-shaking**para que el servicio solo se incluya en tu bundle de JavaScript si realmente se usa
44
44
45
-
This is the recommended approach for most services.
45
+
Este es el enfoque recomendado para la mayoría de los servicios.
46
46
47
-
## Injecting a service
47
+
## Inyectando un servicio
48
48
49
-
Once you've created a service with `providedIn: 'root'`, you can inject it anywhere in your application using the `inject()`function from`@angular/core`.
49
+
Una vez que has creado un servicio con `providedIn: 'root'`, puedes inyectarlo en cualquier parte de tu aplicación usando la función `inject()`de`@angular/core`.
50
50
51
-
### Injecting into a component
51
+
### Inyectando en un componente
52
52
53
53
```angular-ts
54
54
import { Component, inject } from '@angular/core';
While`providedIn: 'root'`covers most use cases, Angular offers additional ways to provide services for specialized scenarios:
98
+
Aunque`providedIn: 'root'`cubre la mayoría de los casos de uso, Angular ofrece formas adicionales de proveer servicios para escenarios especializados:
99
99
100
-
-**Component-specific instances** - When components need their own isolated service instances
101
-
-**Manual configuration** - For services that require runtime configuration
102
-
-**Factory providers** - For dynamic service creation based on runtime conditions
103
-
-**Value providers** - For providing configuration objects or constants
100
+
-**Instancias específicas de componente** - Cuando los componentes necesitan sus propias instancias aisladas de servicio
101
+
-**Configuración manual** - Para servicios que requieren configuración en tiempo de ejecución
102
+
-**Proveedores factory** - Para creación dinámica de servicios basada en condiciones de tiempo de ejecución
103
+
-**Proveedores de valor** - Para proveer objetos de configuración o constantes
104
104
105
-
You can learn more about these advanced patterns in the next guide: [defining dependency providers](/guide/di/defining-dependency-providers).
105
+
Puedes aprender más sobre estos patrones avanzados en la siguiente guía: [definiendo proveedores de dependencias](/guide/di/defining-dependency-providers).
0 commit comments