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
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.
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`.
Copy file name to clipboardExpand all lines: adev-es/src/content/guide/http/http-resource.md
+31-31Lines changed: 31 additions & 31 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,31 +1,31 @@
1
-
# Reactive data fetching with`httpResource`
1
+
# Obtención reactiva de datos con`httpResource`
2
2
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.
4
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.
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.
6
6
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).
8
8
9
-
## `Using httpResource`
9
+
## `Usando httpResource`
10
10
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.
12
12
13
13
14
-
You can define an HTTP resource by returning a url:
14
+
Puedes definir un recurso HTTP devolviendo una URL:
15
15
16
16
```ts
17
17
userId=input.required<string>();
18
18
19
-
user=httpResource(() =>`/api/user/${userId()}`); //A reactive function as argument
19
+
user=httpResource(() =>`/api/user/${userId()}`); //Una función reactiva como argumento
20
20
```
21
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.
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.
24
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`.
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.
26
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.
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.
29
29
30
30
```ts
31
31
user=httpResource(() => ({
@@ -44,39 +44,39 @@ user = httpResource(() => ({
44
44
}));
45
45
```
46
46
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`.
48
48
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.
50
50
51
51
```angular-html
52
52
@if(user.hasValue()) {
53
53
<user-details user="[user.value()]">
54
54
} @else if (user.error()) {
55
-
<div>Could not load user information</div>
55
+
<div>No se pudo cargar la información del usuario</div>
56
56
} @else if (user.isLoading()) {
57
-
<div>Loading user info...</div>
57
+
<div>Cargando información del usuario...</div>
58
58
}
59
59
```
60
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()`.
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()`.
62
62
63
-
### Response types
63
+
### Tipos de respuestas
64
64
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`:
66
66
67
67
```ts
68
-
httpResource.text(() => ({ … })); //returns a string in value()
68
+
httpResource.text(() => ({ … })); //devuelve un string en value()
69
69
70
-
httpResource.blob(() => ({ … })); //returns a Blob object in value()
70
+
httpResource.blob(() => ({ … })); //devuelve un objeto Blob en value()
71
71
72
-
httpResource.arrayBuffer(() => ({ … })); //returns an ArrayBuffer in value()
72
+
httpResource.arrayBuffer(() => ({ … })); //devuelve un ArrayBuffer en value()
73
73
```
74
74
75
-
## Response parsing and validation
75
+
## Análisis y validación de respuestas
76
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`.
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.
78
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.
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.
80
80
81
81
```ts
82
82
const starWarsPersonSchema =z.object({
@@ -96,11 +96,11 @@ export class CharacterViewer {
96
96
}
97
97
```
98
98
99
-
## Testing an httpResource
99
+
## Probando un httpResource
100
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.
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.
102
102
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`.
0 commit comments