Skip to content

Commit c5fca6c

Browse files
ricardochlSplaktar
authored andcommitted
translate: translations for DI guides
Fixes #34
1 parent 5377fed commit c5fca6c

17 files changed

+2745
-666
lines changed

adev-es/src/app/sub-navigation-data.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -297,45 +297,45 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
297297
],
298298
},
299299
{
300-
label: 'Dependency Injection',
300+
label: 'Inyección de Dependencias',
301301
children: [
302302
{
303-
label: 'Overview',
303+
label: 'Visión general',
304304
path: 'guide/di',
305305
contentPath: 'guide/di/overview',
306306
},
307307
{
308-
label: 'Understanding dependency injection',
308+
label: 'Entendiendo la inyección de dependencias',
309309
path: 'guide/di/dependency-injection',
310310
contentPath: 'guide/di/dependency-injection',
311311
},
312312
{
313-
label: 'Creating an injectable service',
313+
label: 'Creando un servicio inyectable',
314314
path: 'guide/di/creating-injectable-service',
315315
contentPath: 'guide/di/creating-injectable-service',
316316
},
317317
{
318-
label: 'Defining dependency providers',
318+
label: 'Definiendo proveedores de dependencias',
319319
path: 'guide/di/dependency-injection-providers',
320320
contentPath: 'guide/di/dependency-injection-providers',
321321
},
322322
{
323-
label: 'Injection context',
323+
label: 'Contexto de inyección',
324324
path: 'guide/di/dependency-injection-context',
325325
contentPath: 'guide/di/dependency-injection-context',
326326
},
327327
{
328-
label: 'Hierarchical injectors',
328+
label: 'Inyectores jerárquicos',
329329
path: 'guide/di/hierarchical-dependency-injection',
330330
contentPath: 'guide/di/hierarchical-dependency-injection',
331331
},
332332
{
333-
label: 'Optimizing injection tokens',
333+
label: 'Optimizando tokens de inyección',
334334
path: 'guide/di/lightweight-injection-tokens',
335335
contentPath: 'guide/di/lightweight-injection-tokens',
336336
},
337337
{
338-
label: 'DI in action',
338+
label: 'DI en acción',
339339
path: 'guide/di/di-in-action',
340340
contentPath: 'guide/di/di-in-action',
341341
},
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
# Creating an injectable service
2+
3+
Service is a broad category encompassing any value, function, or feature that an application needs.
4+
A service is typically a class with a narrow, well-defined purpose.
5+
A component is one type of class that can use DI.
6+
7+
Angular distinguishes components from services to increase modularity and reusability.
8+
By separating a component's view-related features from other kinds of processing, you can make your component classes lean and efficient.
9+
10+
Ideally, a component's job is to enable the user experience and nothing more.
11+
A component should present properties and methods for data binding, to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a model).
12+
13+
A component can delegate certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console.
14+
By defining such processing tasks in an injectable service class, you make those tasks available to any component.
15+
You can also make your application more adaptable by configuring different providers of the same kind of service, as appropriate in different circumstances.
16+
17+
Angular does not enforce these principles.
18+
Angular helps you follow these principles by making it easy to factor your application logic into services and make those services available to components through DI.
19+
20+
## Service examples
21+
22+
Here's an example of a service class that logs to the browser console:
23+
24+
<docs-code header="src/app/logger.service.ts (class)" language="typescript">
25+
export class Logger {
26+
log(msg: unknown) { console.log(msg); }
27+
error(msg: unknown) { console.error(msg); }
28+
warn(msg: unknown) { console.warn(msg); }
29+
}
30+
</docs-code>
31+
32+
Services can depend on other services.
33+
For example, here's a `HeroService` that depends on the `Logger` service, and also uses `BackendService` to get heroes.
34+
That service in turn might depend on the `HttpClient` service to fetch heroes asynchronously from a server:
35+
36+
<docs-code header="src/app/hero.service.ts" language="typescript"
37+
highlight="[7,8,12,13]">
38+
import { inject } from "@angular/core";
39+
40+
export class HeroService {
41+
private heroes: Hero[] = [];
42+
43+
private backend = inject(BackendService);
44+
private logger = inject(Logger);
45+
46+
async getHeroes() {
47+
// Fetch
48+
this.heroes = await this.backend.getAll(Hero);
49+
// Log
50+
this.logger.log(`Fetched ${this.heroes.length} heroes.`);
51+
return this.heroes;
52+
}
53+
}
54+
</docs-code>
55+
56+
## Creating an injectable service
57+
58+
The Angular CLI provides a command to create a new service. In the following example, you add a new service to an existing application.
59+
60+
To generate a new `HeroService` class in the `src/app/heroes` folder, follow these steps:
61+
62+
1. Run this [Angular CLI](/tools/cli) command:
63+
64+
<docs-code language="sh">
65+
ng generate service heroes/hero
66+
</docs-code>
67+
68+
This command creates the following default `HeroService`:
69+
70+
<docs-code header="src/app/heroes/hero.service.ts (CLI-generated)" language="typescript">
71+
import { Injectable } from '@angular/core';
72+
73+
@Injectable({
74+
providedIn: 'root',
75+
})
76+
export class HeroService {}
77+
</docs-code>
78+
79+
The `@Injectable()` decorator specifies that Angular can use this class in the DI system.
80+
The metadata, `providedIn: 'root'`, means that the `HeroService` is provided throughout the application.
81+
82+
Add a `getHeroes()` method that returns the heroes from `mock.heroes.ts` to get the hero mock data:
83+
84+
<docs-code header="src/app/heroes/hero.service.ts" language="typescript">
85+
import { Injectable } from '@angular/core';
86+
import { HEROES } from './mock-heroes';
87+
88+
@Injectable({
89+
// declares that this service should be created
90+
// by the root application injector.
91+
providedIn: 'root',
92+
})
93+
export class HeroService {
94+
getHeroes() {
95+
return HEROES;
96+
}
97+
}
98+
</docs-code>
99+
100+
For clarity and maintainability, it is recommended that you define components and services in separate files.
101+
102+
## Injecting services
103+
104+
To inject a service as a dependency into a component, you can declare a class field representing the dependency and use Angular's `inject` function to initialize it.
105+
106+
The following example specifies the `HeroService` in the `HeroListComponent`.
107+
The type of `heroService` is `HeroService`.
108+
109+
<docs-code header="src/app/heroes/hero-list.component.ts" language="typescript">
110+
import { inject } from "@angular/core";
111+
112+
export class HeroListComponent {
113+
private heroService = inject(HeroService);
114+
}
115+
</docs-code>
116+
117+
It is also possible to inject a service into a component using the component's constructor:
118+
119+
<docs-code header="src/app/heroes/hero-list.component.ts (constructor signature)" language="typescript">
120+
constructor(private heroService: HeroService)
121+
</docs-code>
122+
123+
The `inject` method can be used in both classes and functions, while the constructor method can naturally only be used in a class constructor. However, in either case a dependency may only be injected in a valid [injection context](guide/di/dependency-injection-context), usually in the construction or initialization of a component.
124+
125+
## Injecting services in other services
126+
127+
When a service depends on another service, follow the same pattern as injecting into a component.
128+
In the following example, `HeroService` depends on a `Logger` service to report its activities:
129+
130+
<docs-code header="src/app/heroes/hero.service.ts" language="typescript"
131+
highlight="[3,9,12]">
132+
import { inject, Injectable } from '@angular/core';
133+
import { HEROES } from './mock-heroes';
134+
import { Logger } from '../logger.service';
135+
136+
@Injectable({
137+
providedIn: 'root',
138+
})
139+
export class HeroService {
140+
private logger = inject(Logger);
141+
142+
getHeroes() {
143+
this.logger.log('Getting heroes.');
144+
return HEROES;
145+
}
146+
}
147+
</docs-code>
148+
149+
In this example, the `getHeroes()` method uses the `Logger` service by logging a message when fetching heroes.
150+
151+
## What's next
152+
153+
<docs-pill-row>
154+
<docs-pill href="/guide/di/dependency-injection-providers" title="Configuring dependency providers"/>
155+
<docs-pill href="/guide/di/dependency-injection-providers#using-an-injectiontoken-object" title="`InjectionTokens`"/>
156+
</docs-pill-row>
Lines changed: 42 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
1-
# Creating an injectable service
1+
# Creando un servicio inyectable
22

3-
Service is a broad category encompassing any value, function, or feature that an application needs.
4-
A service is typically a class with a narrow, well-defined purpose.
5-
A component is one type of class that can use DI.
3+
Un servicio es una categoría amplia que abarca cualquier valor, función o característica que una aplicación necesita.
4+
Un servicio es típicamente una clase con un propósito específico y bien definido.
5+
Un componente es un tipo de clase que puede usar DI.
66

7-
Angular distinguishes components from services to increase modularity and reusability.
8-
By separating a component's view-related features from other kinds of processing, you can make your component classes lean and efficient.
7+
Angular distingue los componentes de los servicios para aumentar la modularidad y reutilización.
8+
Al separar las características relacionadas con la vista de un componente de otros tipos de procesamiento, puedes hacer que tus clases de componente sean eficientes y ligeras.
99

10-
Ideally, a component's job is to enable the user experience and nothing more.
11-
A component should present properties and methods for data binding, to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a model).
10+
Idealmente, el trabajo de un componente es habilitar la experiencia del usuario y nada más.
11+
Un componente debe presentar propiedades y métodos para el enlace de datos, para mediar entre la vista (renderizada por la plantilla) y la lógica de la aplicación (que a menudo incluye alguna noción de un modelo).
1212

13-
A component can delegate certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console.
14-
By defining such processing tasks in an injectable service class, you make those tasks available to any component.
15-
You can also make your application more adaptable by configuring different providers of the same kind of service, as appropriate in different circumstances.
13+
Un componente puede delegar ciertas tareas a los servicios, como obtener datos del servidor, validar la entrada del usuario o registrar directamente en la consola.
14+
Al definir tales tareas de procesamiento en una clase de servicio inyectable, haces que esas tareas estén disponibles para cualquier componente.
15+
También puedes hacer que tu aplicación sea más adaptable configurando diferentes proveedores del mismo tipo de servicio, según sea apropiado en diferentes circunstancias.
1616

17-
Angular does not enforce these principles.
18-
Angular helps you follow these principles by making it easy to factor your application logic into services and make those services available to components through DI.
17+
Angular no hace cumplir estos principios.
18+
Angular te ayuda a seguir estos principios haciendo que sea fácil factorizar la lógica de tu aplicación en servicios y hacer que esos servicios estén disponibles para los componentes a través de DI.
1919

20-
## Service examples
20+
## Ejemplos de servicios
2121

22-
Here's an example of a service class that logs to the browser console:
22+
Aquí tienes un ejemplo de una clase de servicio que registra en la consola del navegador:
2323

2424
<docs-code header="src/app/logger.service.ts (class)" language="typescript">
2525
export class Logger {
@@ -29,9 +29,9 @@ export class Logger {
2929
}
3030
</docs-code>
3131

32-
Services can depend on other services.
33-
For example, here's a `HeroService` that depends on the `Logger` service, and also uses `BackendService` to get heroes.
34-
That service in turn might depend on the `HttpClient` service to fetch heroes asynchronously from a server:
32+
Los servicios pueden depender de otros servicios.
33+
Por ejemplo, aquí tienes un `HeroService` que depende del servicio `Logger`, y también usa `BackendService` para obtener héroes.
34+
Ese servicio a su vez podría depender del servicio `HttpClient` para obtener héroes de forma asíncrona desde un servidor:
3535

3636
<docs-code header="src/app/hero.service.ts" language="typescript"
3737
highlight="[7,8,12,13]">
@@ -47,25 +47,25 @@ export class HeroService {
4747
// Fetch
4848
this.heroes = await this.backend.getAll(Hero);
4949
// Log
50-
this.logger.log(`Fetched ${this.heroes.length} heroes.`);
50+
this.logger.log(`Obtenidos ${this.heroes.length} héroes.`);
5151
return this.heroes;
5252
}
5353
}
5454
</docs-code>
5555

56-
## Creating an injectable service
56+
## Creando un servicio inyectable
5757

58-
The Angular CLI provides a command to create a new service. In the following example, you add a new service to an existing application.
58+
El Angular CLI proporciona un comando para crear un nuevo servicio. En el siguiente ejemplo, agregas un nuevo servicio a una aplicación existente.
5959

60-
To generate a new `HeroService` class in the `src/app/heroes` folder, follow these steps:
60+
Para generar una nueva clase `HeroService` en la carpeta `src/app/heroes`, sigue estos pasos:
6161

62-
1. Run this [Angular CLI](/tools/cli) command:
62+
1. Ejecuta este comando [Angular CLI](/tools/cli):
6363

6464
<docs-code language="sh">
6565
ng generate service heroes/hero
6666
</docs-code>
6767

68-
This command creates the following default `HeroService`:
68+
Este comando crea el siguiente `HeroService` por defecto:
6969

7070
<docs-code header="src/app/heroes/hero.service.ts (CLI-generated)" language="typescript">
7171
import { Injectable } from '@angular/core';
@@ -76,18 +76,18 @@ import { Injectable } from '@angular/core';
7676
export class HeroService {}
7777
</docs-code>
7878

79-
The `@Injectable()` decorator specifies that Angular can use this class in the DI system.
80-
The metadata, `providedIn: 'root'`, means that the `HeroService` is provided throughout the application.
79+
El decorador `@Injectable()` especifica que Angular puede usar esta clase en el sistema DI.
80+
Los metadatos, `providedIn: 'root'`, significan que el `HeroService` se provee en toda la aplicación.
8181

82-
Add a `getHeroes()` method that returns the heroes from `mock.heroes.ts` to get the hero mock data:
82+
Agrega un método `getHeroes()` que devuelva los héroes de `mock.heroes.ts` para obtener los datos simulados de héroes:
8383

8484
<docs-code header="src/app/heroes/hero.service.ts" language="typescript">
8585
import { Injectable } from '@angular/core';
8686
import { HEROES } from './mock-heroes';
8787

8888
@Injectable({
89-
// declares that this service should be created
90-
// by the root application injector.
89+
// declara que este servicio debe ser creado
90+
// por el inyector de la aplicación raíz.
9191
providedIn: 'root',
9292
})
9393
export class HeroService {
@@ -97,14 +97,14 @@ export class HeroService {
9797
}
9898
</docs-code>
9999

100-
For clarity and maintainability, it is recommended that you define components and services in separate files.
100+
Para claridad y mantenibilidad, se recomienda que definas componentes y servicios en archivos separados.
101101

102-
## Injecting services
102+
## Inyectando servicios
103103

104-
To inject a service as a dependency into a component, you can declare a class field representing the dependency and use Angular's `inject` function to initialize it.
104+
Para inyectar un servicio como dependencia en un componente, puedes declarar un campo de clase que represente la dependencia y usar la función `inject` de Angular para inicializarlo.
105105

106-
The following example specifies the `HeroService` in the `HeroListComponent`.
107-
The type of `heroService` is `HeroService`.
106+
El siguiente ejemplo especifica el `HeroService` en el `HeroListComponent`.
107+
El tipo de `heroService` es `HeroService`.
108108

109109
<docs-code header="src/app/heroes/hero-list.component.ts" language="typescript">
110110
import { inject } from "@angular/core";
@@ -114,18 +114,18 @@ export class HeroListComponent {
114114
}
115115
</docs-code>
116116

117-
It is also possible to inject a service into a component using the component's constructor:
117+
También es posible inyectar un servicio en un componente usando el constructor del componente:
118118

119119
<docs-code header="src/app/heroes/hero-list.component.ts (constructor signature)" language="typescript">
120120
constructor(private heroService: HeroService)
121121
</docs-code>
122122

123-
The `inject` method can be used in both classes and functions, while the constructor method can naturally only be used in a class constructor. However, in either case a dependency may only be injected in a valid [injection context](guide/di/dependency-injection-context), usually in the construction or initialization of a component.
123+
El método `inject` puede ser usado tanto en clases como en funciones, mientras que el método constructor naturalmente solo puede ser usado en un constructor de clase. Sin embargo, en cualquier caso una dependencia solo puede ser inyectada en un [contexto de inyección](guide/di/dependency-injection-context) válido, usualmente en la construcción o inicialización de un componente.
124124

125-
## Injecting services in other services
125+
## Inyectando servicios en otros servicios
126126

127-
When a service depends on another service, follow the same pattern as injecting into a component.
128-
In the following example, `HeroService` depends on a `Logger` service to report its activities:
127+
Cuando un servicio depende de otro servicio, sigue el mismo patrón que inyectar en un componente.
128+
En el siguiente ejemplo, `HeroService` depende de un servicio `Logger` para reportar sus actividades:
129129

130130
<docs-code header="src/app/heroes/hero.service.ts" language="typescript"
131131
highlight="[3,9,12]">
@@ -146,11 +146,11 @@ export class HeroService {
146146
}
147147
</docs-code>
148148

149-
In this example, the `getHeroes()` method uses the `Logger` service by logging a message when fetching heroes.
149+
En este ejemplo, el método `getHeroes()` usa el servicio `Logger` registrando un mensaje cuando obtiene héroes.
150150

151-
## What's next
151+
## Próximos pasos
152152

153153
<docs-pill-row>
154-
<docs-pill href="/guide/di/dependency-injection-providers" title="Configuring dependency providers"/>
154+
<docs-pill href="/guide/di/dependency-injection-providers" title="Configurando proveedores de dependencias"/>
155155
<docs-pill href="/guide/di/dependency-injection-providers#using-an-injectiontoken-object" title="`InjectionTokens`"/>
156156
</docs-pill-row>

0 commit comments

Comments
 (0)