baeckerman83
baeckerman83

Reputation: 335

vue2 & promise How to Update Variable?

I have a class with a variable in the constructor, I try to make a ajax request and update a variable. But the variable is not in my scope. what can I do?

import Axios from "axios";

class ajaxTest{
    constructor() {
        this.resultOfAjax=" Mein Test";
    }

    set(id){
        return new Promise(function(resolve, reject) {
            Axios.get('/api/v1/ajax/'+id)  
            .then(function (response) {
                this.resultOfAjax=response.data;
                resolve(200);
                console.log("Test");
            });
        })
    }
}
export default ajaxTest;

Also I try to update my loadingCircle variable, but it is not working. I think it is the same mistake. Is this right?

const app = new Vue({
    el: '#app',
    data: {
      loadingCircle: true,
      ajaxTest: new ajaxTest()
    },
    methods: {
      handleClick: function(id) {
        console.log("Das ist ein Test die ID ist:"+id); 
        this.ajaxTest.set(id).then( function(status){
          console.log("Status "+status);
          this.loadingCircle=false;
        });
      }
    },
    components: {
      examplecomponent
    }
});

Upvotes: 0

Views: 30

Answers (1)

edwin
edwin

Reputation: 2821

If you use a function, then the this inside it is not the same as the this outside. The solution is to use the fat arrow notation instead.

const app = new Vue({
    el: '#app',
    data: {
      loadingCircle: true,
      ajaxTest: new ajaxTest()
    },
    methods: {
      handleClick: (id) => {
        console.log("Das ist ein Test die ID ist:"+id); 
        this.ajaxTest.set(id).then( (status) => {
          console.log("Status "+status);
          this.loadingCircle=false;
        });
      }
    },
    components: {
      examplecomponent
    }
});

Upvotes: 2

Related Questions