Obtain data from an Observable

0

I have been studying a bit about the Observables in Typescript, specifically in Ionic 3, I understand that to be able to read the data of an Observable I must subscribe to it, but until now I have only been able to use the data within the subscribe

import { DatabaseProvider from '../../providers/database/database'};
import { Observable } from 'rxjs/Observable';

export interface Data{id:string; name:string; dascription:string;}

export class HomePage{
private Datos: Observable<Data[]>:
datos: any[];

    constructor(private readonly database: DatabaseProvider){
        this.Datos= databse.getDocuments('items');
        this.Datos.subscribe(result => this.datos = result);
        console.log(this.Datos) // el resultado es undefined
    }
}

However, if I create a foreach () with the result variable and start printing the values inside the subscribe if the data appears, some idea of how to get them out of the subscribe

    
asked by Raul Uriel Andrade Soto 09.02.2018 в 17:02
source

1 answer

1

Is that you can only use them in there: An observable returns data asynchronously, similar to a promise. When you subscribe, you are simply passing the function to which it will be called (in the future) when it issues something:

//defino cómo se procesarán los datos
function funcionObservadora (datos) {
   //proceso los datos recibidos, si se ejecuta este código
   //es porque se ha emitido algo.
}

//me subscribo al observable
miObservable.subscribe(funcionObservadora);
//el observable aún no ha emitido nada

So that you understand how to handle asynchrony: your constructor does declare intentions , it is other methods that have to perform the actions:

//versión muy simplificada de un Observable

class ObservableMock {
   constructor() {
     this.observers=[];
     this.interval=null;
     this.emitido=0;
   }
   
   subscribe(func) {
     this.observers.push(func);
     if (this.interval==null) {
       this.interval=setInterval(()=>this.emite(),1000);
     }
   }
   
   emite() {
   debugger;
     this.emitido++;
     this.observers.forEach(obs => obs("Emitiendo "+ this.emitido));
     if (this.emitido==5) clearInterval(this.interval);
   }
}

let mock= new ObservableMock();

class Observador {
  constructor() {
     //subscripción hecha aquí
     mock.subscribe(this.metodoObservador);
  }
  
  //aquí se gestionan los datos recibidos realmente
  metodoObservador(datos) {
    console.log("Recibiendo datos: ",datos);
  }
}

new Observador();
    
answered by 09.02.2018 в 17:11