正如标题所说,我想重构我的代码。 当我想将API调用放在外部提供程序中时,我有一个问题(如果有一天我必须使用它,我只会导入新的.ts文件) ,我无法达到"天气" DATAS。
这是我的代码:
import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
// importation des plugins
import { Geolocation } from '@ionic-native/geolocation';
import { OpenWeatherProvider, Weather } from '../../providers/meteo/open-weather-provider'
import { Test } from '../test/test';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from "rxjs/Rx"
@Component({
selector: 'geoloc',
templateUrl: 'geoloc.html'
})
export class Geoloc {
public lng = 0;
public lat = 0;
//Observable de type Weather (classe exportée dans open-weather-provider)
public weather;
//public weather$: Subscription;
public Meteo: Weather;
constructor(public navCtrl: NavController, private geolocation: Geolocation, public platform: Platform, public OWP: OpenWeatherProvider) {
platform.ready().then(() =>{
//Appel a l'initialisation
this.loadPosition();
});
}
//This is the function i would like to put into the ts.file
loadPosition(){
//Appel methode coords GPS
this.geolocation.getCurrentPosition().then((resp) => {
this.lng = resp.coords.longitude;
this.lat = resp.coords.latitude;
//Reception des donnees de l'API OWP (OpenWeatherProvider)
this.weather = this.OWP.getWeatherPerLatLng(this.lat,this.lng);
this.weather.subscribe(data=>{
this.Meteo=data ;
}); // end subscribe
});
}
这是我用于API的提供者:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Rx";
import { Http, Response } from "@angular/http";
@Injectable()
export class OpenWeatherProvider {
apikey = 'ea91a7eab8e8b73b433086eb0244fc94';
WeatherArr: Array<String> = [];
testWeather: Weather;
constructor(public http: HttpClient) {
}
getWeatherPerLatLng(lat,lng) {
return this.http.get<Weather>('http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+lng+'&units=metric&appid='+ this.apikey);
// this.http.get<Weather>('http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+lng+'&units=metric&appid='+ this.apikey).subscribe(
// data => {
// console.log("HTTP GET PROVIDER API",data)
// return data; // you should never have application logic in a provider
// });
}
}
export interface Weather{
coord: {
lon: number,
lat: number
},
weather: [
{
id: number,
main: String,
description: String,
icon: String
}
],
base: String,
main: {
temp: number,
pressure: number,
humidity: number,
temp_min: number,
temp_max: number
},
visibility: number,
wind: {
speed: number,
deg: number
},
clouds: {
all: number
},
dt: number,
sys: {
type: number,
id: number,
message: number,
country: String,
sunrise: number,
sunset: number
},
id: number,
name: String,
cod: number
}
我将loadposition()函数剪切/粘贴到我创建的文件中,但我无法从中读取数据。 有没有解决方案,或者我只需要让功能在那里?
谢谢你的时间!