Skip to content

Commit 3087762

Browse files
ricardochlSplaktar
authored andcommitted
translate: translations for HttpClient guides
Fixes #34
1 parent ff22744 commit 3087762

File tree

15 files changed

+1307
-307
lines changed

15 files changed

+1307
-307
lines changed

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

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -427,30 +427,35 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
427427
],
428428
},
429429
{
430-
label: 'HTTP Client',
430+
label: 'Cliente HTTP',
431431
children: [
432432
{
433-
label: 'Overview',
433+
label: 'Visión general',
434434
path: 'guide/http',
435435
contentPath: 'guide/http/overview',
436436
},
437437
{
438-
label: 'Setting up HttpClient',
438+
label: 'Configurando HttpClient',
439439
path: 'guide/http/setup',
440440
contentPath: 'guide/http/setup',
441441
},
442442
{
443-
label: 'Making requests',
443+
label: 'Realizando solicitudes HTTP',
444444
path: 'guide/http/making-requests',
445445
contentPath: 'guide/http/making-requests',
446446
},
447447
{
448-
label: 'Intercepting requests and responses',
448+
label: 'Obtención reactiva de datos con httpResource',
449+
path: 'guide/http/http-resource',
450+
contentPath: 'guide/http/http-resource',
451+
},
452+
{
453+
label: 'Interceptando peticiones y respuestas',
449454
path: 'guide/http/interceptors',
450455
contentPath: 'guide/http/interceptors',
451456
},
452457
{
453-
label: 'Testing',
458+
label: 'Pruebas',
454459
path: 'guide/http/testing',
455460
contentPath: 'guide/http/testing',
456461
},
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# Reactive data fetching with `httpResource`
2+
3+
IMPORTANT: `httpResource` is [experimental](reference/releases#experimental). It's ready for you to try, but it might change before it is stable.
4+
5+
`httpResource` is a reactive wrapper around `HttpClient` that gives you the request status and response as signals. You can thus use these signals with `computed`, `effect`, `linkedSignal`, or any other reactive API. Because it's built on top of `HttpClient`, `httpResource` supports all the same features, such as interceptors.
6+
7+
For more about Angular's `resource` pattern, see [Async reactivity with `resource`](/guide/signals/resource).
8+
9+
## `Using httpResource`
10+
11+
TIP: Make sure to include `provideHttpClient` in your application providers. See [Setting up HttpClient](/guide/http/setup) for details.
12+
13+
14+
You can define an HTTP resource by returning a url:
15+
16+
```ts
17+
userId = input.required<string>();
18+
19+
user = httpResource(() => `/api/user/${userId()}`); // A reactive function as argument
20+
```
21+
22+
`httResource` is reactive, meaning that whenever one of the signal it depends on changes (like `userId`), the resource will emit a new http request.
23+
If a request is already pending, the resource cancels the outstanding request before issuing a new one.
24+
25+
HELPFUL: `httpResource` differs from the `HttpClient` as it initiates the request _eagerly_. In contrast, the `HttpClient` only initiates requests upon subscription to the returned `Observable`.
26+
27+
For more advanced requests, you can define a request object similar to the request taken by `HttpClient`.
28+
Each property of the request object that should be reactive should be composed by a signal.
29+
30+
```ts
31+
user = httpResource(() => ({
32+
url: `/api/user/${userId()}`,
33+
method: 'GET',
34+
headers: {
35+
'X-Special': 'true',
36+
},
37+
params: {
38+
'fast': 'yes',
39+
},
40+
reportProgress: true,
41+
withCredentials: true,
42+
transferCache: true,
43+
keepalive: true,
44+
}));
45+
```
46+
47+
TIP: Avoid using `httpResource` for _mutations_ like `POST` or `PUT`. Instead, prefer directly using the underlying `HttpClient` APIs.
48+
49+
The signals of the `httpResource` can be used in the template to control which elements should be displayed.
50+
51+
```angular-html
52+
@if(user.hasValue()) {
53+
<user-details user="[user.value()]">
54+
} @else if (user.error()) {
55+
<div>Could not load user information</div>
56+
} @else if (user.isLoading()) {
57+
<div>Loading user info...</div>
58+
}
59+
```
60+
61+
HELPFUL: Reading the `value` signal on a `resource` that is in error state throws at runtime. It is recommended to guard `value` reads with `hasValue()`.
62+
63+
### Response types
64+
65+
By default, `httpResource` returns and parses the response as JSON. However, you can specify alternate return with additional functions on `httpResource`:
66+
67+
```ts
68+
httpResource.text(() => ({ … })); // returns a string in value()
69+
70+
httpResource.blob(() => ({ … })); // returns a Blob object in value()
71+
72+
httpResource.arrayBuffer(() => ({ … })); // returns an ArrayBuffer in value()
73+
```
74+
75+
## Response parsing and validation
76+
77+
When fetching data, you may want to validate responses against a predefined schema, often using popular open-source libraries like [Zod](https://zod.dev) or [Valibot](https://valibot.dev). You can integrate validation libraries like this with `httpResource` by specifying a `parse` option. The return type of the `parse` function determines the type of the resource's `value`.
78+
79+
The following example uses Zod to parse and validate the response from the [StarWars API](https://swapi.info/). The resource is then typed the same as the output type of Zod’s parsing.
80+
81+
```ts
82+
const starWarsPersonSchema = z.object({
83+
name: z.string(),
84+
height: z.number({ coerce: true }),
85+
edited: z.string().datetime(),
86+
films: z.array(z.string()),
87+
});
88+
89+
export class CharacterViewer {
90+
id = signal(1);
91+
92+
swPersonResource = httpResource(
93+
() => `https://swapi.info/api/people/${this.id()}`,
94+
{ parse: starWarsPersonSchema.parse }
95+
);
96+
}
97+
```
98+
99+
## Testing an httpResource
100+
101+
Because `httpResource` is a wrapper around `HttpClient`, you can test `httpResource` with the exact same APIs as `HttpClient`. See [HttpClient Testing](/guide/http/testing) for details.
102+
103+
The following example shows a unit test for code using `httpResource`.
104+
105+
```ts
106+
TestBed.configureTestingModule({
107+
providers: [
108+
provideHttpClient(),
109+
provideHttpClientTesting(),
110+
],
111+
});
112+
113+
const id = signal(0);
114+
const mockBackend = TestBed.inject(HttpTestingController);
115+
const response = httpResource(() => `/data/${id()}`, {injector: TestBed.inject(Injector)});
116+
TestBed.tick(); // Triggers the effect
117+
const firstRequest = mockBackend.expectOne('/data/0');
118+
firstRequest.flush(0);
119+
120+
// Ensures the values are propagated to the httpResource
121+
await TestBed.inject(ApplicationRef).whenStable();
122+
123+
expect(response.value()).toEqual(0);
124+
```

adev-es/src/content/guide/http/http-resource.md

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
1-
# Reactive data fetching with `httpResource`
1+
# Obtención reactiva de datos con `httpResource`
22

3-
IMPORTANT: `httpResource` is [experimental](reference/releases#experimental). It's ready for you to try, but it might change before it is stable.
3+
IMPORTANTE: `httpResource` es [experimental](reference/releases#experimental). Está listo para que lo pruebes, pero podría cambiar antes de que sea estable.
44

5-
`httpResource` is a reactive wrapper around `HttpClient` that gives you the request status and response as signals. You can thus use these signals with `computed`, `effect`, `linkedSignal`, or any other reactive API. Because it's built on top of `HttpClient`, `httpResource` supports all the same features, such as interceptors.
5+
`httpResource` es un envoltorio reactivo alrededor de `HttpClient` que te proporciona el estado de la solicitud y la respuesta como señales. Por lo tanto, puedes usar estas señales con `computed`, `effect`, `linkedSignal`, o cualquier otra API reactiva. Debido a que está construido sobre `HttpClient`, `httpResource` admite todas las mismas características, como interceptores.
66

7-
For more about Angular's `resource` pattern, see [Async reactivity with `resource`](/guide/signals/resource).
7+
Para más información sobre el patrón `resource` de Angular, consulta [Reactividad asíncrona con `resource`](/guide/signals/resource).
88

9-
## `Using httpResource`
9+
## `Usando httpResource`
1010

11-
TIP: Make sure to include `provideHttpClient` in your application providers. See [Setting up HttpClient](/guide/http/setup) for details.
11+
CONSEJO: Asegúrate de incluir `provideHttpClient` en los providers de tu aplicación. Consulta [Configurar HttpClient](/guide/http/setup) para más detalles.
1212

1313

14-
You can define an HTTP resource by returning a url:
14+
Puedes definir un recurso HTTP devolviendo una URL:
1515

1616
```ts
1717
userId = input.required<string>();
1818

19-
user = httpResource(() => `/api/user/${userId()}`); // A reactive function as argument
19+
user = httpResource(() => `/api/user/${userId()}`); // Una función reactiva como argumento
2020
```
2121

22-
`httResource` is reactive, meaning that whenever one of the signal it depends on changes (like `userId`), the resource will emit a new http request.
23-
If a request is already pending, the resource cancels the outstanding request before issuing a new one.
22+
`httpResource` es reactivo, lo que significa que cada vez que una de las señales de las que depende cambie (como `userId`), el recurso emitirá una nueva solicitud HTTP.
23+
Si una solicitud ya está pendiente, el recurso cancela la solicitud pendiente antes de emitir una nueva.
2424

25-
HELPFUL: `httpResource` differs from the `HttpClient` as it initiates the request _eagerly_. In contrast, the `HttpClient` only initiates requests upon subscription to the returned `Observable`.
25+
ÚTIL: `httpResource` difiere de `HttpClient` ya que inicia la solicitud de manera _inmediata_. En contraste, `HttpClient` solo inicia solicitudes al suscribirse al `Observable` devuelto.
2626

27-
For more advanced requests, you can define a request object similar to the request taken by `HttpClient`.
28-
Each property of the request object that should be reactive should be composed by a signal.
27+
Para solicitudes más avanzadas, puedes definir un objeto de solicitud similar al que toma `HttpClient`.
28+
Cada propiedad del objeto de solicitud que debe ser reactiva debe estar compuesta por una señal.
2929

3030
```ts
3131
user = httpResource(() => ({
@@ -44,39 +44,39 @@ user = httpResource(() => ({
4444
}));
4545
```
4646

47-
TIP: Avoid using `httpResource` for _mutations_ like `POST` or `PUT`. Instead, prefer directly using the underlying `HttpClient` APIs.
47+
CONSEJO: Evita usar `httpResource` para _mutaciones_ como `POST` o `PUT`. En su lugar, prefiere usar directamente las APIs subyacentes de `HttpClient`.
4848

49-
The signals of the `httpResource` can be used in the template to control which elements should be displayed.
49+
Las signals del `httpResource` se pueden usar en la plantilla para controlar qué elementos deben mostrarse.
5050

5151
```angular-html
5252
@if(user.hasValue()) {
5353
<user-details user="[user.value()]">
5454
} @else if (user.error()) {
55-
<div>Could not load user information</div>
55+
<div>No se pudo cargar la información del usuario</div>
5656
} @else if (user.isLoading()) {
57-
<div>Loading user info...</div>
57+
<div>Cargando información del usuario...</div>
5858
}
5959
```
6060

61-
HELPFUL: Reading the `value` signal on a `resource` that is in error state throws at runtime. It is recommended to guard `value` reads with `hasValue()`.
61+
ÚTIL: Leer la signal `value` en un `resource` que está en estado de error lanza una excepción en tiempo de ejecución. Se recomienda proteger las lecturas de `value` con `hasValue()`.
6262

63-
### Response types
63+
### Tipos de respuestas
6464

65-
By default, `httpResource` returns and parses the response as JSON. However, you can specify alternate return with additional functions on `httpResource`:
65+
Por defecto, `httpResource` devuelve y analiza la respuesta como JSON. Sin embargo, puedes especificar un retorno alternativo con funciones adicionales en `httpResource`:
6666

6767
```ts
68-
httpResource.text(() => ({ … })); // returns a string in value()
68+
httpResource.text(() => ({ … })); // devuelve un string en value()
6969

70-
httpResource.blob(() => ({ … })); // returns a Blob object in value()
70+
httpResource.blob(() => ({ … })); // devuelve un objeto Blob en value()
7171

72-
httpResource.arrayBuffer(() => ({ … })); // returns an ArrayBuffer in value()
72+
httpResource.arrayBuffer(() => ({ … })); // devuelve un ArrayBuffer en value()
7373
```
7474

75-
## Response parsing and validation
75+
## Análisis y validación de respuestas
7676

77-
When fetching data, you may want to validate responses against a predefined schema, often using popular open-source libraries like [Zod](https://zod.dev) or [Valibot](https://valibot.dev). You can integrate validation libraries like this with `httpResource` by specifying a `parse` option. The return type of the `parse` function determines the type of the resource's `value`.
77+
Al obtener datos, es posible que quieras validar las respuestas contra un esquema predefinido, a menudo usando bibliotecas populares de código abierto como [Zod](https://zod.dev) o [Valibot](https://valibot.dev). Puedes integrar bibliotecas de validación como estas con `httpResource` especificando una opción `parse`. El tipo de retorno de la función `parse` determina el tipo del `value` del recurso.
7878

79-
The following example uses Zod to parse and validate the response from the [StarWars API](https://swapi.info/). The resource is then typed the same as the output type of Zod’s parsing.
79+
El siguiente ejemplo usa Zod para analizar y validar la respuesta de la [API de StarWars](https://swapi.info/). El recurso se tipa igual que el tipo de salida del análisis de Zod.
8080

8181
```ts
8282
const starWarsPersonSchema = z.object({
@@ -96,11 +96,11 @@ export class CharacterViewer {
9696
}
9797
```
9898

99-
## Testing an httpResource
99+
## Probando un httpResource
100100

101-
Because `httpResource` is a wrapper around `HttpClient`, you can test `httpResource` with the exact same APIs as `HttpClient`. See [HttpClient Testing](/guide/http/testing) for details.
101+
Debido a que `httpResource` es un envoltorio alrededor de `HttpClient`, puedes probar `httpResource` con exactamente las mismas APIs que `HttpClient`. Consulta [Pruebas de HttpClient](/guide/http/testing) para más detalles.
102102

103-
The following example shows a unit test for code using `httpResource`.
103+
El siguiente ejemplo muestra una prueba unitaria para código que usa `httpResource`.
104104

105105
```ts
106106
TestBed.configureTestingModule({
@@ -113,11 +113,11 @@ TestBed.configureTestingModule({
113113
const id = signal(0);
114114
const mockBackend = TestBed.inject(HttpTestingController);
115115
const response = httpResource(() => `/data/${id()}`, {injector: TestBed.inject(Injector)});
116-
TestBed.tick(); // Triggers the effect
116+
TestBed.tick(); // TDispara el efecto
117117
const firstRequest = mockBackend.expectOne('/data/0');
118118
firstRequest.flush(0);
119119

120-
// Ensures the values are propagated to the httpResource
120+
// Asegura que los valores se propaguen al httpResource
121121
await TestBed.inject(ApplicationRef).whenStable();
122122

123123
expect(response.value()).toEqual(0);

0 commit comments

Comments
 (0)