在HarmonyOS中實現(xiàn)天氣服務(wù)功能
介紹
本案例通過調(diào)用云端的天氣服務(wù)API,在HarmonyOS中實現(xiàn)天氣服務(wù)功能。開發(fā)者們可根據(jù)不同業(yè)務(wù)場景,在本案例的基礎(chǔ)上集成自己的天氣服務(wù)管理者模塊。
開發(fā)環(huán)境要求
● DevEco Studio版本:DevEco Studio 3.1 Release
● HarmonyOS SDK版本:API version 9
工程要求
- API9
- Stage模型
正文
前置條件
在本案例中,實現(xiàn)天氣服務(wù)的功能需要聚合數(shù)據(jù)平臺提供的天氣預報云服務(wù)。開發(fā)者需要在聚合數(shù)據(jù)平臺注冊和登錄賬號,然后申請?zhí)鞖忸A報的API,并通過實名認證獲取自己的Key。通過Key,我們就可以通過http數(shù)據(jù)請求的方式調(diào)用天氣預報的API,而官方會為每名開發(fā)者提供50次的每日免費調(diào)用次數(shù)。
代碼結(jié)構(gòu)
entry/src/main
├─ module.json5 //模塊的配置文件
├─ resources //資源文件集
└─ ets
├─ XL_Modules
│ └─ XL_WeatherServiceManager.ts //天氣服務(wù)管理者ts模塊
├─ pages
│ └─ Index.ets //主頁面
└─ entryability
└─ EntryAbility.ts //UIAbility類
關(guān)鍵代碼
XL_WeatherServiceManager.ts:
//導入http模塊
import http from '@ohos.net.http'
//定義日志標簽
const TAG1 = '------[XL_WeatherServiceManager inquire] '
//提供云服務(wù)接口的網(wǎng)址片段
const Weather_Url_Part:string = "http://apis.juhe.cn/simpleWeather/query?key="
//開發(fā)者在聚合數(shù)據(jù)的請求Key(需要自行填入)
const key:string = ......
//聲明一個專用于記錄天氣信息的數(shù)據(jù)類型
declare type RealTime_Weather_Result = {
//實時數(shù)據(jù)
realtime: any,
//今日整體數(shù)據(jù)
today:any,
//是否成功拉取
isFinished: boolean
}
/*
異步函數(shù): 獲取對應(yīng)城市的天氣數(shù)據(jù)
*/
async function Pull_Weather_Data(cityName: string, Tag: string):Promise<RealTime_Weather_Result>{
//預定義輸出
var output = {
realtime: null,
today: null,
isFinished: false
}
//實例化一個http請求任務(wù)類
let httpRequest = http.createHttp();
//拼接url,以供訪問服務(wù)器
let URL = Weather_Url_Part+key+'&city='+cityName
//調(diào)用異步方法request
await httpRequest.request(
URL,
{
//設(shè)置請求方法的類型
method: http.RequestMethod.GET,
}).then((data) => {
//提取http響應(yīng)的關(guān)鍵內(nèi)容
let Weather_Info = JSON.parse(data.result.toString())
//當關(guān)鍵內(nèi)容中所攜帶的錯誤碼為0時,表示成功拉取了天氣數(shù)據(jù)
if(Weather_Info?.error_code == 0){
console.info(TAG1+'Succeed! Obtain the weather data')
//在日志欄打印天氣信息
console.info(TAG1+JSON.stringify(Weather_Info?.result?.realtime))
console.info(TAG1+JSON.stringify(Weather_Info?.result?.future[0]))
//存取天氣信息
output.realtime = Weather_Info?.result?.realtime
output.today = Weather_Info?.result?.future[0]
output.isFinished = true
}else{
console.error(Tag+Weather_Info?.reason)
}
}).catch(err => console.error(Tag + 'Http request failed, err: ' + `${err}`))
//銷毀http任務(wù)類
httpRequest.destroy()
//輸出
return output
}
//默認導出的靜態(tài)型模塊類
class XL_WeatherServiceManager {
//查詢某城市天氣的方法
public static async inquire(cityName: string):Promise<RealTime_Weather_Result>{
return await Pull_Weather_Data(cityName, TAG1)
}
/*
* 敬請期待
*/
}
export default XL_WeatherServiceManager
在XL_WeatherServiceManager.ts中,我們通過http請求的方式,獲取并解析服務(wù)器所回饋的天氣預報信息。值得一提的是,我們創(chuàng)建了類XL_WeatherServiceManager,此類有個靜態(tài)公共方法inquire調(diào)用了拉取天氣信息的異步函數(shù),并且XL_WeatherServiceManager是默認導出的。因此,我們可以在頁面中導入XL_WeatherServiceManager,并通過執(zhí)行require方法調(diào)用獲取天氣信息的功能。
import XL_WeatherServiceManager from 'ets/XL_Modules/XL_WeatherServiceManager'
......
let result = await XL_WeatherServiceManager.inquire('北京')
......
在頁面中調(diào)用
Index.ets(偽代碼):
//導入自定義的天氣服務(wù)管理模塊
import XL_WeatherServiceManager from 'ets/XL_Modules/XL_WeatherServiceManager'
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
@State cityName:string = ''
@State currentTemperature:string = ''
@State currentWeather:string = ''
@State todayTemperature:string = ''
@State translateY:number = 700
build() {
......
Search({
placeholder: '請輸入城市名'
})
//添加回調(diào)函數(shù)
.onSubmit((cityName:string)=>{
this.Search(cityName)
})
......
......
}
//自定義異步方法
async Search(cityName:string){
//通過天氣服務(wù)管理者調(diào)用inquire方法,并傳入城市名參數(shù)
let res = await XL_WeatherServiceManager.inquire(cityName)
if(res.isFinished){
//根據(jù)需求讀取信息
this.currentTemperature = res.realtime.temperature
this.currentWeather = res.realtime.info
this.todayTemperature = res.today.temperature
this.cityName = cityName
this.translateY = 0
}
}
}