Observables, promises are driving me crazy

0

I have a small code where I read a json to get the current online version of my data the idea is then compare with the local version saved with sqlite and if it is smaller then download the rest of json and update my BD.

    
   this.http.get('https://mi.json').subscribe(
      data => {
        this.VO = data['numero'];       
        console.log(this.VO);       
      }
    );
   console.log(this.VO); 

I know it may seem silly but I can not understand why I can not use the value of my variable outside the observable, that means if or if within the positive response of the same I should consult my BD and compare the data or is there another way? to give me a basic idea helps me to continue from now thanks

    
asked by Miguel Rojas 06.06.2018 в 00:08
source

2 answers

1

You can not use the variable outside the observable because the observables are asynchronous. In other words: You have no way to ensure that once the get request is executed, the server will return the data instantaneously .

Each request you make takes a while to execute, both get() as post() . In order to process the returned data you have to do it within the observable or send a callback that is executed when receiving the data:

obtenerUsuarios(onrecived: (Array<Users>) => void)
{
  this.http.get('https://mi.json').subscribe(
    data => {
      onrecived(data);
    }
  );
}

// uso
obtenerUsuarios(usuarios=>{
   console.log(usuarios)
});
    
answered by 06.06.2018 в 00:47
0

The Observer is a design pattern. The function of the Observables is to detect changes, in your case, if another user changes the variable of your database, it detects the change and updates automatically without needing to refresh the page.

The observables have two functions (so to speak). The first is the Obsevable , which is the one that is always pending a change, is always observing, worth the redundancy. The second one is the Subscribe , which is the one that you put up, that is responsible for observer's abstraction, this means that the subscribe requests the Observable to execute its function, in turn the Observable You can call the subscriber every time you detect a change. It's like a kind of promise.

If you want more info about this, I'll leave the link Oberver pattern

I see that you only put the part of the subscribe , you can save a variable in the component and thus use the subscribe information outside of this function as you do in your code.

 this.http.get('https://mi.json').subscribe(
  data => {
    this.VO = data['numero'];       
    console.log(this.VO);       
  }
);
console.log(this.VO); 

You can use the variable VO to make the comparisons, this will always change whenever the Observable detects a change (It is important to mention that it depends where the observable is)

    
answered by 06.06.2018 в 00:30