【问题标题】:Angular Yahoo Weather APIAngular 雅虎天气 API
【发布时间】:2018-06-30 08:28:53
【问题描述】:

我对 Yahoo Weather API 有疑问。我应该如何请求从 Yahoo Weather API 获取数据?

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class WeatherService {
  constructor(private http: HttpClient) { }

  getWeatherForecast(city: string): Observable<any> {
   const url = 'https://query.yahooapis.com/v1/public/yql?q=select wind from 
   weather.forecast where woeid=2460286';
   return this.http.get(url);
  }
}

【问题讨论】:

  • 请使用实际代码而不是图片来编辑您的问题。谢谢
  • 您当前收到 404,可能是因为 URL 中的空格。您可以尝试在该网址上使用encodeURI,并使用已编码的网址吗?此外,当我点击该 URL 时,我会返回 XML,这可能会导致您出现问题,因为 HttpClient 默认会尝试将结果解析为 JSON
  • 我已经更改了query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D) 的网址%22greenland%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys 来自文档,但结果相同。
  • 如果您检查浏览器的开发者工具网络面板,它是否尝试连接到正确的 URL?那个 URL 似乎对我有用?如果做不到这一点,您能否创建一个重现该问题的 StackBlitz?谢谢
  • 你是对的。我在应用程序中有 In-memory-web-api。我认为这是一个问题。

标签: javascript angular api yahoo weather


【解决方案1】:

工作示例:stackblitz

您唯一的问题是您忘记在您的 url 字符串中添加:&format=json

返回的数据默认为XML格式。

【讨论】:

    【解决方案2】:

    这是一个简单的例子,但我希望它对你有所帮助。我将在这里使用一个名为 axios 的库:

    const url = "https://query.yahooapis.com/v1/public/yql?q=select item.condition from weather.forecast where woeid in (select woeid from geo.places(1) where text='Sunderland') and u='c'&format=json";
      
        const getWeatherData = () => {
             axios.get(url)
            .then(res => console.log(res.data.query.results.channel.item.condition))
            .catch(err => console.log(err.data))
        }
        
        getWeatherData();
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.12.0/axios.min.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 2012-08-16
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多