【问题标题】:API not being called from Web未从 Web 调用 API
【发布时间】:2019-04-08 12:09:06
【问题描述】:

我正在尝试从 API 调用一些数据来构建一个基本的天气应用程序作为练习。

我正在我的 chrome 浏览器上使用检查元素来查看控制台是否会在日志中显示我的数据,但无济于事。

我在这方面遇到了障碍,我觉得我只是缺少一些代码或做一些小错误。 任何帮助,将不胜感激。

以下代码来自我的 weather.ts 提供者

constructor(public http: HttpClient)
  {
    console.log('Hello WeatherProvider Provider');
    //this.url = 'http://api.openweathermap.org/data/2.5/weather?q=dublin,Ireland&APPID=b90245073a8392aec69a261861286c3b';

  }

  // getting weather info from API with a custom city and country
  getWeather(city, country):Observable<any> 
  {
    return this.http.get('https://api.openweathermap.org/data/2.5/weather?q='+city+','+country+'&APPID='+this.apiKey);
  }

}

构造函数中的console.log出现在控制台中,但没有其他内容。

代码 以下来自我的 home.ts 页面

export class HomePage
{
  weather: any;
  location: 
  {
    city: string,
    country: string
  }

  constructor(public navCtrl: NavController, private weatherProvider:WeatherProvider) 
  {

  }

  ionWillEnter()
  {
    this.location = {city: 'dublin', country: 'Ireland'}

    this.weatherProvider.getWeather(this.location.city, this.location.country).subscribe(weather => {
      console.log(weather);
    });
  }

}

console.log(天气);是我的最终目标。让它按预期出现在控制台中。

【问题讨论】:

    标签: angular typescript ionic3


    【解决方案1】:

    您拼错了生命周期方法名称。

    您可能想使用ionViewWillEnterngOnInit

    【讨论】:

      【解决方案2】:

      Angular 有生命周期方法。 NgonInit 最初会被调用,所以你需要把你的代码放在 onInit 方法中。 参考这里的其他生命周期钩子 https://angular.io/guide/lifecycle-hooks

      【讨论】:

        猜你喜欢
        • 2019-06-14
        • 2021-11-06
        • 2013-08-29
        • 1970-01-01
        • 2013-07-25
        • 2019-03-30
        • 2015-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多