How to pass value from service to var?

Asked

Viewed 39 times

1

I have a REST service to seek the visitor’s values. However, I cannot 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?

Result printed inside the promise

Resultado impresso dentro da *promisse*

Result that is printed outside the promise

Resultado que é impresso fora da *promisse*

  • You can show what is being presented in each case?

  • @LINQ Includes two images with the outputs

  • That one created is outside the object, should be after the data(). I think that’s just the problem with your code. What’s that this.VisitorService? how you’re adding it to the Vue object?

1 answer

0

You are using the scope this within the Omise, this makes it 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 doing so, Visitor will be fed into Vue and so, taking effect on html if you are using it. What you cannot do is use the console.log call outside the scope of the file, hoping it has the correct value. The Promise serves exactly for this, but to access the scope of Vue, you need to first store in a variable your instance because this will be within the context of Vue and not Vue.

  • In fact I had already declared the Visitor within the date(). I will edit to leave this information together with the example. also following your example, ends up returning the component..

  • I did an update, see if it got better to understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.