Skip to content

Commit 0c47b71

Browse files
docs: translate rx-library.md (angular-hispano#346)
Fixes angular-hispano#144
1 parent 7521004 commit 0c47b71

File tree

2 files changed

+149
-51
lines changed

2 files changed

+149
-51
lines changed

aio/content/guide/rx-library.en.md

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# The RxJS library
2+
3+
Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change ([Wikipedia](https://en.wikipedia.org/wiki/Reactive_programming)). RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. See ([RxJS Docs](https://rxjs.dev/guide/overview)).
4+
5+
RxJS provides an implementation of the `Observable` type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables. These utility functions can be used for:
6+
7+
* Converting existing code for async operations into observables
8+
* Iterating through the values in a stream
9+
* Mapping values to different types
10+
* Filtering streams
11+
* Composing multiple streams
12+
13+
## Observable creation functions
14+
15+
RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on. For example:
16+
17+
18+
<code-example path="rx-library/src/simple-creation.ts" region="promise" header="Create an observable from a promise"></code-example>
19+
20+
<code-example path="rx-library/src/simple-creation.ts" region="interval" header="Create an observable from a counter"></code-example>
21+
22+
<code-example path="rx-library/src/simple-creation.ts" region="event" header="Create an observable from an event"></code-example>
23+
24+
<code-example path="rx-library/src/simple-creation.ts" region="ajax" header="Create an observable that creates an AJAX request"></code-example>
25+
26+
## Operators
27+
28+
Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections. For example, RxJS defines operators such as `map()`, `filter()`, `concat()`, and `flatMap()`.
29+
30+
Operators take configuration options, and they return a function that takes a source observable. When executing this returned function, the operator observes the source observable’s emitted values, transforms them, and returns a new observable of those transformed values. Here is a simple example:
31+
32+
<code-example path="rx-library/src/operators.ts" header="Map operator"></code-example>
33+
34+
You can use _pipes_ to link operators together. Pipes let you combine multiple functions into a single function. The `pipe()` function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
35+
36+
A set of operators applied to an observable is a recipe&mdash;that is, a set of instructions for producing the values you’re interested in. By itself, the recipe doesn’t do anything. You need to call `subscribe()` to produce a result through the recipe.
37+
38+
Here’s an example:
39+
40+
<code-example path="rx-library/src/operators.1.ts" header="Standalone pipe function"></code-example>
41+
42+
The `pipe()` function is also a method on the RxJS `Observable`, so you use this shorter form to define the same operation:
43+
44+
<code-example path="rx-library/src/operators.2.ts" header="Observable.pipe function"></code-example>
45+
46+
### Common operators
47+
48+
RxJS provides many operators, but only a handful are used frequently. For a list of operators and usage samples, visit the [RxJS API Documentation](https://rxjs.dev/api).
49+
50+
<div class="alert is-helpful">
51+
Note that, for Angular apps, we prefer combining operators with pipes, rather than chaining. Chaining is used in many RxJS examples.
52+
</div>
53+
54+
| Area | Operators |
55+
| :------------| :----------|
56+
| Creation | `from`,`fromEvent`, `of` |
57+
| Combination | `combineLatest`, `concat`, `merge`, `startWith` , `withLatestFrom`, `zip` |
58+
| Filtering | `debounceTime`, `distinctUntilChanged`, `filter`, `take`, `takeUntil` |
59+
| Transformation | `bufferTime`, `concatMap`, `map`, `mergeMap`, `scan`, `switchMap` |
60+
| Utility | `tap` |
61+
| Multicasting | `share` |
62+
63+
## Error handling
64+
65+
In addition to the `error()` handler that you provide on subscription, RxJS provides the `catchError` operator that lets you handle known errors in the observable recipe.
66+
67+
For instance, suppose you have an observable that makes an API request and maps to the response from the server. If the server returns an error or the value doesn’t exist, an error is produced. If you catch this error and supply a default value, your stream continues to process values rather than erroring out.
68+
69+
Here's an example of using the `catchError` operator to do this:
70+
71+
<code-example path="rx-library/src/error-handling.ts" header="catchError operator"></code-example>
72+
73+
### Retry failed observable
74+
75+
Where the `catchError` operator provides a simple path of recovery, the `retry` operator lets you retry a failed request.
76+
77+
Use the `retry` operator before the `catchError` operator. It resubscribes to the original source observable, which can then re-run the full sequence of actions that resulted in the error. If this includes an HTTP request, it will retry that HTTP request.
78+
79+
The following converts the previous example to retry the request before catching the error:
80+
81+
<code-example path="rx-library/src/retry-on-error.ts" header="retry operator"></code-example>
82+
83+
<div class="alert is-helpful">
84+
85+
Do not retry **authentication** requests, since these should only be initiated by user action. We don't want to lock out user accounts with repeated login requests that the user has not initiated.
86+
87+
</div>
88+
89+
## Naming conventions for observables
90+
91+
Because Angular applications are mostly written in TypeScript, you will typically know when a variable is an observable. Although the Angular framework does not enforce a naming convention for observables, you will often see observables named with a trailing “$” sign.
92+
93+
This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to simply use the same name with or without the “$”.
94+
95+
For example:
96+
97+
<code-example path="rx-library/src/naming-convention.ts" header="Naming observables"></code-example>

aio/content/guide/rx-library.md

+52-51
Original file line numberDiff line numberDiff line change
@@ -1,97 +1,98 @@
1-
# The RxJS library
1+
# La Librería de RxJS
22

3-
Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change ([Wikipedia](https://en.wikipedia.org/wiki/Reactive_programming)). RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. See ([RxJS Docs](https://rxjs.dev/guide/overview)).
3+
La programación Reactiva es un paradigma de programación asincrónico interesado en los flujos de datos y la propagación al cambio ([Wikipedia](https://en.wikipedia.org/wiki/Reactive_programming)). RxJS (Por sus siglas en Inglés, "Reactive Extensions for JavaScript") es una librería para programación reactiva usando obvservables que hacen más fácil la creación de código asincrono o basado en callbacks. Ver ([RxJS Docs](https://rxjs.dev/guide/overview)).
44

5-
RxJS provides an implementation of the `Observable` type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables. These utility functions can be used for:
5+
RxJS proporciona una implementación del tipo `Observable`, el cual es necesitado hasta que el tipo de dato sea parte del lenguaje y hasta que los navegadores ofrezcan un soporte. La librería también proporciona funciones de utilería para la creación y trabajo con observables. Dichas funciones de utilería pueden ser usadas para:
66

7-
* Converting existing code for async operations into observables
8-
* Iterating through the values in a stream
9-
* Mapping values to different types
10-
* Filtering streams
11-
* Composing multiple streams
7+
* Convertir código existente para operaciones asíncronas en observables.
8+
* Iterar a través de valores en un flujo de datos.
9+
* Mappear valores en tipos de datos diferentes.
10+
* Filtrar flujos de datos.
11+
* Composición de múltiplos flujos.
1212

13-
## Observable creation functions
13+
## Creación de funciones observables
1414

15-
RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on. For example:
15+
RxJS ofrece un sin fin de funciones que pueden ser usadas para crear nuevos observables. Estas funciones pueden simplificar el proceso de creación de observables desde cosas como eventos, temporizadores, promesas, etc. Por ejemplo:
1616

17+
<code-example path="rx-library/src/simple-creation.ts" region="promise" header="Crear un observable desde una promesa"></code-example>
1718

18-
<code-example path="rx-library/src/simple-creation.ts" region="promise" header="Create an observable from a promise"></code-example>
19+
<code-example path="rx-library/src/simple-creation.ts" region="interval" header="Crear un observable desde un contador"></code-example>
1920

20-
<code-example path="rx-library/src/simple-creation.ts" region="interval" header="Create an observable from a counter"></code-example>
21+
<code-example path="rx-library/src/simple-creation.ts" region="event" header="Crear un observable desde un evento"></code-example>
2122

22-
<code-example path="rx-library/src/simple-creation.ts" region="event" header="Create an observable from an event"></code-example>
23+
<code-example path="rx-library/src/simple-creation.ts" region="ajax" header="Crear un observable que crea una petición AJAX"></code-example>
2324

24-
<code-example path="rx-library/src/simple-creation.ts" region="ajax" header="Create an observable that creates an AJAX request"></code-example>
25+
{@a operators}
26+
## Operadores
2527

26-
## Operators
28+
Los operadores son funciones que construyen sobre la fundación de los observables para tener una manipulación más sofisticada de las colecciones. Por ejemplo, RxJS define operadores como `map()`, `filter()`, `concat()`, y `flatMap()`.
2729

28-
Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections. For example, RxJS defines operators such as `map()`, `filter()`, `concat()`, and `flatMap()`.
30+
Los operadores toman las opciones de configuración y después regresan una función que toma la fuente observable. Cuando ejecutamos esta función regresada, el operador observa los valores fuente emitidos por el observable, los transforma y regresa un nuevo observable de esos valores transformados. Aquí un ejemplo sencillo:
2931

30-
Operators take configuration options, and they return a function that takes a source observable. When executing this returned function, the operator observes the source observable’s emitted values, transforms them, and returns a new observable of those transformed values. Here is a simple example:
32+
<code-example path="rx-library/src/operators.ts" header="Operador Map"></code-example>
3133

32-
<code-example path="rx-library/src/operators.ts" header="Map operator"></code-example>
34+
Puedes usar _pipes_ para enlazar más de un operador. Los Pipes te permiten combinar múltiples funciones en una sola. La función `pipe()` tiene como argumentos las funciones que quieres que combine y regresa una nueva función que, una vez ejecutada, corre las funciones en una sequencia.
3335

34-
You can use _pipes_ to link operators together. Pipes let you combine multiple functions into a single function. The `pipe()` function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
36+
Un conjunto de operadores aplicados a un observable no es más que una receta la cuál, es un conjunto de instrucciones para producir los valores que te interesan. Por sí misma, esta receta no hace nada. Necesitarás llamar a la función `subscribe()` para producir un resultado a través dicha receta.
3537

36-
A set of operators applied to an observable is a recipe&mdash;that is, a set of instructions for producing the values you’re interested in. By itself, the recipe doesn’t do anything. You need to call `subscribe()` to produce a result through the recipe.
38+
A continuación un ejemplo:
3739

38-
Here’s an example:
40+
<code-example path="rx-library/src/operators.1.ts" header="Función pipe autónoma"></code-example>
3941

40-
<code-example path="rx-library/src/operators.1.ts" header="Standalone pipe function"></code-example>
42+
La función `pipe()` es también un `Observable` en RxJS, así que usas esta manera más sencilla para definir la misma operación:
4143

42-
The `pipe()` function is also a method on the RxJS `Observable`, so you use this shorter form to define the same operation:
44+
<code-example path="rx-library/src/operators.2.ts" header="Función Observable.pipe"></code-example>
4345

44-
<code-example path="rx-library/src/operators.2.ts" header="Observable.pipe function"></code-example>
46+
### Operadores Comunes
4547

46-
### Common operators
47-
48-
RxJS provides many operators, but only a handful are used frequently. For a list of operators and usage samples, visit the [RxJS API Documentation](https://rxjs.dev/api).
48+
RxJS propociona muchos operadores pero solo algunos se usan con frecuencia. Para una lista de los operadores y su uso visita la [Documentación de RxJS](https://rxjs.dev/api).
4949

5050
<div class="alert is-helpful">
51-
Note that, for Angular apps, we prefer combining operators with pipes, rather than chaining. Chaining is used in many RxJS examples.
51+
Nota: Para aplicaciones creadas con Angular preferiremos combinar operadores con pipes, en lugar de hacer cadenas. El encadenamiento es usado en muchos ejemplos de RxJS.
5252
</div>
5353

54-
| Area | Operators |
54+
| Area | Operador |
5555
| :------------| :----------|
56-
| Creation | `from`,`fromEvent`, `of` |
57-
| Combination | `combineLatest`, `concat`, `merge`, `startWith` , `withLatestFrom`, `zip` |
58-
| Filtering | `debounceTime`, `distinctUntilChanged`, `filter`, `take`, `takeUntil` |
59-
| Transformation | `bufferTime`, `concatMap`, `map`, `mergeMap`, `scan`, `switchMap` |
60-
| Utility | `tap` |
61-
| Multicasting | `share` |
56+
| Creación | `from`,`fromEvent`, `of` |
57+
| Combinación | `combineLatest`, `concat`, `merge`, `startWith` , `withLatestFrom`, `zip` |
58+
| Filtrado| `debounceTime`, `distinctUntilChanged`, `filter`, `take`, `takeUntil` |
59+
| Transformación | `bufferTime`, `concatMap`, `map`, `mergeMap`, `scan`, `switchMap` |
60+
| Utilería | `tap` |
61+
| Multidifusión | `share` |
62+
63+
## Manejo de Errores
6264

63-
## Error handling
65+
En adición con el manejador de `error()` que te ayuda con la subscripción, RxJS proporciona el operador `catchError` que te permite manejar los errores conocidos en un medio de observables.
6466

65-
In addition to the `error()` handler that you provide on subscription, RxJS provides the `catchError` operator that lets you handle known errors in the observable recipe.
67+
Por ejemplo, supongamos que tienes un observable que hace una petición a una API y mapea la respuesta de un servidor. Si el servidor regresa un error o el valor no existe entonces se produciría un error. Si hacemos un catch de este error y le proporcionamos un valor por defecto entonces el flujo continuará, en lugar de simplemente mandarnos un error.
6668

67-
For instance, suppose you have an observable that makes an API request and maps to the response from the server. If the server returns an error or the value doesn’t exist, an error is produced. If you catch this error and supply a default value, your stream continues to process values rather than erroring out.
6869

69-
Here's an example of using the `catchError` operator to do this:
70+
Aquí un ejemplo de como usar el operador `catchError` para hacer esto:
7071

71-
<code-example path="rx-library/src/error-handling.ts" header="catchError operator"></code-example>
72+
<code-example path="rx-library/src/error-handling.ts" header="Operador catchError"></code-example>
7273

73-
### Retry failed observable
74+
### Observable de reintentos fallidos
7475

75-
Where the `catchError` operator provides a simple path of recovery, the `retry` operator lets you retry a failed request.
76+
Donde el operador `catchError` ayuda a crear un camino simple para recuperarnos, el operador `retry` te permite reintentar una petición fallida.
7677

77-
Use the `retry` operator before the `catchError` operator. It resubscribes to the original source observable, which can then re-run the full sequence of actions that resulted in the error. If this includes an HTTP request, it will retry that HTTP request.
78+
Usa el operador `retry` antes del operador `catchError`. Dicho operador te re-subscribe a la fuente original del observable, la cual puede re-ejecutar una secuencia llena de acciones que resultaron en el error en primer lugar. Si esto incluye una petición HTTP, entonces el operador reintentará hacer la petición HTTP.
7879

79-
The following converts the previous example to retry the request before catching the error:
80+
En el siguiente ejemplo usamos el ejemplo anterior pero ahora intentamos hacer la petición primero antes de obtener el error.
8081

81-
<code-example path="rx-library/src/retry-on-error.ts" header="retry operator"></code-example>
82+
<code-example path="rx-library/src/retry-on-error.ts" header="Operador retry"></code-example>
8283

8384
<div class="alert is-helpful">
8485

85-
Do not retry **authentication** requests, since these should only be initiated by user action. We don't want to lock out user accounts with repeated login requests that the user has not initiated.
86+
No intentar hacer peticiones con una **autenticación** , ya que estas deben ser inicialiadas por una acción del usuario. No nos gustaría bloquear cuentas de usuario con solicitudes de inicio de sesión repetidas que el mismo usuario no ha iniciado.
8687

8788
</div>
8889

89-
## Naming conventions for observables
90+
## Nombrando convenciones para los observables
9091

91-
Because Angular applications are mostly written in TypeScript, you will typically know when a variable is an observable. Although the Angular framework does not enforce a naming convention for observables, you will often see observables named with a trailing “$” sign.
92+
Debido a que en su mayoría las aplicaciones de Angular están escritas en TypeScript, típicamente sabrás cuando una variable es un observable. Aunque el framework de Angular no impone una convención de nombrado de observables, frecuentemente veras a los observables nombrados con el signo de “$” al final.
9293

93-
This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to simply use the same name with or without the “$”.
94+
Esto puede llegar a ser muy útil cuando escaneamos rapidamente el código y miramos el valor de los observables. Además, si quieres tener una propiedad para almacenara el valor más reciente de un observable entonce puede ser muy conveniente simplemente usar el nombre con o sin el “$”.
9495

95-
For example:
96+
Por ejemplo:
9697

97-
<code-example path="rx-library/src/naming-convention.ts" header="Naming observables"></code-example>
98+
<code-example path="rx-library/src/naming-convention.ts" header="Nombrando observables"></code-example>

0 commit comments

Comments
 (0)