2016-10-06 1 views
1

У меня есть код ниже и продолжаю получать свойство «weatherData» не существует в типе «XMLHttpRequest». Предполагается, что выведет погоду в консоли.TypeScript с этим. параметр

class WeatherService { 
    public weatherData; 

    public getWeather(callback) { 
     let url = `http://api.openweathermap.org/data/2.5/weather?API=&APPID=d43debb0b9a3919fef3f0f689e82583e&q=${this.city}`; 
     let request = new XMLHttpRequest(); 
     request.addEventListener('load', function() { 
      // parse weather data from Ajax call 
      this.weatherData = JSON.parse(request.responseText); 
      // invoke callback to notify that we are done 
      callback(); 
     }) 
     request.open('GET', url); 
     request.send(); 
    } 

    constructor(private city: string) { } 
} 

// create instance of weather service for Seattle 
let service = new WeatherService('Seattle'); 

// invoke the service to get weather data for Seattle 
service.getWeather(() => { 
    console.log(service.weatherData); 
}); 
+0

вы действительно хотите добавить 'weatherData' в объект запроса? потому что 'this' в' request.addEventListener ('load') 'обратный вызов относится к' запросу', а не к классу 'WeatherService'. –

ответ

3

this находится в addEventListener обратного вызова request, но вы можете переопределить с помощью синтаксиса функции стрелки для обратного вызова, так что this будет ваш экземпляр класса вместо:

request.addEventListener('load',() => { 
    // parse weather data from Ajax call 
    this.weatherData = JSON.parse(request.responseText); 
    // invoke callback to notify that we are done 
    callback(); 
}) 
+0

В этом случае '' '' '' '' метод 'getWeather', а не класс? Как он хочет «console.log», кажется, он хочет добавить «weatherData» в класс службы. –

+1

Нет, 'this' будет экземпляром класса' service', потому что 'getWeather' называется' service.getWeather'. – JohnnyHK

+0

Да, метод стрельбы отлично работал. –

Смежные вопросы