Aqu铆 un peque帽o aporte adicional al funcionamiento del SwitchMap(), por Alan Buscaglia maestro del curso de Typescript con Angular
Manejo de rutas
Qu茅 aprender谩s sobre Angular Router y programaci贸n modular
Creando rutas
Creando el Home
P谩gina de categor铆as
Evitando doble subscribe
RouterLink y RouterActive
Ruta 404
Detalle de cada producto
Parametros URL
M贸dulos
LazyLoading y CodeSplitting
Programaci贸n Modular
Vistas anidadas
Creando el CMS Module
Creando en Website Module
Creando un Shared Module
Precarga de m贸dulos
Precarga de m贸dulos
All Modules y Custom Strategy
QuickLink Strategy
Guardianes
Conoce a los Guardianes
Implementando redirects
Estado de login
Guard para Admin
CanDeactivate
Deployment
Netlify Deployment
Despedida
Despedida
Create an account or log in
Keep learning for free! Join and start boosting your career
One of the main problems with observables is Callback Hell. Nesting N number of subscriptions, one inside the other, makes your code very difficult to maintain and read.
Using promises, you can solve this easily with async/await
. But if we talk about observables, our best friend, the RxJS library, comes in to provide a solution.
A common example of this issue in Angular is like the following:
readAndUpdate(): void { // Example of callback hell this.apiService.getProduct(1) .subscribe(res => { this.apiService.updateProduct(1, { name: 'New product name' }) .subscribe(res2 => { // ...}); }); }); }
Where a request is being made for reading a product and immediately updating the product. Generating a subscribe
within a subscribe.
Perhaps, up to two subscribes
is acceptable, but it is not recommended to continue with that code structure and it is possible to solve it as follows.
import { switchMap } from 'rxjs/operators'; readAndUpdate(): void { // Solution callback hell this.apiService.getProduct(1) .pipe( switchMap(products => this.apiService.updateProduct(1, { name: 'New name' }) ) ) .subscribe(res => { // Updated product}); }
Importing switchMap
from rxjs/operators
, what this function does is to receive the data emitted by one observable, and immediately use it as input for the second one. This way, the code is cleaner and more professional.
Contributed by: Kevin Fiorentino.
Contributions 8
Questions 3
Aqu铆 un peque帽o aporte adicional al funcionamiento del SwitchMap(), por Alan Buscaglia maestro del curso de Typescript con Angular
Recomiendo mucho ver el siguiente video para profundizar un poco mas en las estrategias para aplanar subscriptions de RXJS
https://www.youtube.com/watch?v=sxjpUNRU_tI&list=PL4vWncexIMYuvT5oCCGpShrRoM0hizLky&index=2
Es cuesti贸n de gustos, pero no me gusta tener c贸digo HTML al interior de un componente.
@Component({
selector: 'app-category',
template: `<app-products
[products]="products"
(loadMore)="onLoadMore()"
></app-products>`,
styleUrls: ['./category.component.scss'],
})
bastante picante el tema de rxjs y sus operators 馃懡
Muy buen curso del profe.Apoyemoslo.
En mi trabajo tengo muchas situaciones as铆. Vengo aprendiendo RxJS con el paso del tiempo a como el proyecto me lo va requiriendo. Y no conoc铆a que era una mala pr谩ctica el tener un susbscribe dentro de otro.
Gracias!!
Se me ocurr铆a otra soluci贸n, usando el operador filter para no tener que hacer esa condici贸n, luego si el switchmap directo y por 煤ltimo el operador take, para que en teor铆a el subscribe se complete
primer comentario!
Want to see more contributions, questions and answers from the community?