Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS http get request

Trying to send an http get request using Vue js. Can't see any problems with the logic, not too experienced using vuejs though.

Keep getting these two errors:

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"

and

TypeError: Cannot read property 'get' of undefined.

var owm = new Vue({
  el: '#owm',
  data: {
    debug: true,
    weather: []
  },
  methods: {
    loadWeather: function() {
      this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=766b78c39446a8fa6313c3b7b2063ade', function(data, status, request){
        if(status == 200)
        {
          this.weather = data;
          console.log(this.weather);
        }
      });
    }
  },
  mounted: function () {
    this.loadWeather();
  }
});

Updated the code using vue resource, the errors are gone but it won't console log any data, what could be wrong?

Vue.use(VueResource);
var owm = new Vue({
  el: '#owm',
  data: {
    weather: []
  },
  methods: {
    loadWeather: function() {
      this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=[API KEY]', function(data, status, request){
        if(status == 200)
        {
          this.weather = data;
          console.log(this.weather);
        }
      });
    }
  },
  mounted: function () {
    this.loadWeather();
  }
});

EDIT: This code works, don't really understand the .then function though and why the request won't work with the callback function but the .then function does.

this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=[API KEY]').then((data) => {
  this.weather = data;
  console.log(this.weather);
like image 634
Znowman Avatar asked Nov 21 '17 09:11

Znowman


1 Answers

I tried a sample on my machine .you are using $http in wrong way. refer the docs.Since $http resolves a promise its callback can be handled inside a then function. This worked for me:

 loadWeather: function() {
    var self=this;
  this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=766b78c39446a8fa6313c3b7b2063ade').then(function(response){
    if(response.status == "200"){
        console.log(response);
    self.weather = response.data.list[0].weather // use self instead of this
    }


  })
like image 103
Manav Mandal Avatar answered Sep 19 '22 00:09

Manav Mandal