Soy nuevo en TypeScript. Entiendo los Observables y los espero. subscribe()
o pipe()
. Pero no entiendo muy bien por qué debajo del código no funciona. Para mayor claridad, la refresh()
La función en la parte inferior necesita:
- Actualizar ubicaciones disponibles desde el servidor;
Ejecute un chequeo de salud en cada una de esas ubicaciones.
getLocations(): Observable<void> { this.locations = []; this.healthCheckService.getLocations() // service returns an Observable .subscribe(location_names => ( location_names.forEach((location_name) => { this.locations.push(new Location({"name": location_name})) }) )); } getHealth(location): void { this.healthCheckService.getHealth(location) .subscribe(health => ( location.health = health, this.isLoaded = true )); } refresh(): void { this.getLocations().subscribe(_ => { this.locations.forEach((location) => { this.getHealth(location); }) }); }
}
Entiendo que tengo que devolver un Observable desde el getLocations()
Función para que sea abonado. Pero desde getLocations()
sí necesita esperar un resultado, me imagino que debo devolver este Observable en la función de suscripción. Sin embargo, eso es sintácticamente no está bien.
Respuestas
1 para la respuesta № 1El tipo de retorno de getLocations
La función es observable. Pero no estás devolviendo ningún observable en él. No tiene declaraciones de devolución dentro de esa función.
getLocations(): Observable<void> {
this.locations = [];
return this.healthCheckService.getLocations()
.do(location_names => (
location_names.forEach((location_name) => {
this.locations.push(new Location({"name": location_name}))
})); //assuming this function returns observable
}
Puedes usar rxjs
do/tap
operador para hacer cambios a su this.location[]
variable.
De esta manera, devolverá un observable y su función de actualización podrá suscribirse a él.
2 para la respuesta № 2
Puedes usar el .do
Funcionar en lugar de suscribirse.
Luego, en la actualización, puedes usar Observable.forkJoin
esperar a todos los getHealth
observables para terminar
getLocations(): Observable<void> {
this.locations = [];
return this.healthCheckService.getLocations()
.do(location_names => (
location_names.forEach((location_name) => {
this.locations.push(new Location({"name": location_name}))
})
));
}
getHealth(location): void {
return this.healthCheckService.getHealth(location)
.do(health => (
location.health = health,
this.isLoaded = true
));
}
refresh(): void {
return this.getLocations().flatMap(_ => {
return Observable.forkJoin(this.locations.map((location) => {
return this.getHealth(location);
}));
});
}