ReferenceError: API не определен (Javascript) - PullRequest
0 голосов
/ 06 мая 2020

Я пытаюсь создать приложение для метео, но мой api не загружается. Когда я вызываю API для получения вывода: ReferenceError: API не определен. Это мое первое приложение (также мой первый вопрос по StackOverflow), это фрагмент:

window.addEventListener('load', () =>{
  let long;
  let lang;
  let temperatureDescription = document.querySelector('.temperature-description');
  let temperatureDegree = document.querySelector('.temperature-degree');
  let locationTimezone = document.querySelector('.location-timezone');
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position=>{
      long = position.coords.longitude;
      lat = position.coords.latitude;
      const proxy = 'https://cors-anyware.herouapp.com/';
      const API = '${proxy}https://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=cc6a4a00070dfbee1327390b072f88d6/${lat},${long}';
    });
    fetch(API).then(response=>{
      return response.json();
    }).then(data=>{
      console.log(data);
      const {
        temperature,
        summary
      }
      = data.currently;
      //set DOM elements from the API
      temperatureDegree.textContent = temperature;
    });
  };
}
);

Кто-нибудь может мне помочь? Спасибо :)

1 Ответ

0 голосов
/ 06 мая 2020

Ваша постоянная переменная API ограничена блоком, это означает, что она доступна только внутри обратного вызова функции getCurrentPosition.

А также, navigator.geolocation.getCurrentPosition асинхронный, вы должны вызвать fetch внутри обратного вызова. в противном случае fetch будет выполняться до того, как браузер определит местоположение lat lon.

window.addEventListener('load', () =>{
  let long;
  let lang;
  let temperatureDescription = document.querySelector('.temperature-description');
  let temperatureDegree = document.querySelector('.temperature-degree');
  let locationTimezone = document.querySelector('.location-timezone');
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position=>{
      long = position.coords.longitude;
      lat = position.coords.latitude;
      const proxy = 'https://cors-anyware.herouapp.com/';
      const API = '${proxy}https://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=cc6a4a00070dfbee1327390b072f88d6/${lat},${long}';

      fetch(API).then(response=>{
          return response.json();
      }).then(data=>{
          console.log(data);
          const {
            temperature,
            summary
          }
         = data.currently;
        //set DOM elements from the API
        temperatureDegree.textContent = temperature;
      });
    });

  };
}
);

...