How to pass value from service to var?

1

I have a REST service to fetch visitor values. However, I can not manipulate the values coming from the service outside the promise .

export default{
  data(){
    return{
      visitor: {}
    }
  }
}

created(){
   this.VisitorService.show(this.visitorStorage)
      .then(visitor => {
        this.visitor = visitor;
        console.log(this.visitor);
        // dentro da promise ok, apresenta o valor.
      }).catch(error =>{
      console.log(error);
    });

    console.log(this.visitor);
    // fora, imprime somente o objeto
}

Does anyone have any idea what I might be doing wrong?

Printed results within promisse

Resultthatisprintedoutofpromisse

    
asked by anonymous 26.06.2017 / 21:15

1 answer

0

You are using the this scope within the promise, this is not using the scope of Vue and soon your variable will not receive the value. Create an access point to the Vue scope with the name of another variable and use this point to make the association later. It would look like this:

export default {
  data() {
    return {
      visitor: {}
    }
  }
}

created() {
  var self = this;

  this.VisitorService.show(this.visitorStorage)
    .then(visitor => {
      self.visitor = visitor;
    }).catch(error => {
      console.log(error);
    });

  // Não pode ser utilizado o console.log logo após uma requisição
  // pois você não tem certeza que a chamada foi finalizada...
  // o correto é utilizar dentro do then da promise como fez.
  // console.log(this.visitor);
}

In this way, the visitor will be fed into the vue and thus taking effect in html if you are using it. What you can not do is use the console.log call outside the scope of the promise expecting it to have the correct value. The promise is exactly for this, but to access the scope of Vue, you need to store a variable in your instance because this will be within the context of the promise and not the vue.

    
26.06.2017 / 21:24