先來看一下效果
本項目界面搭建基于ArkUI中TS擴展的聲明式開發范式,
數據接口是[和風(天氣預報)],
使用ArkUI自帶的網絡請求調用接口。
我想要實現的一個功能是,查詢當前城市的實時天氣,
目前已實現的功能有:
- 默認查詢北京的天氣預報
- 查看當前的天氣
- 查看未來七天的天氣
通過本項目,你能學到的知識有:
- 網絡請求
- 條件渲染
- 狀態管理
先來看一下
接下來開始正文,
我們先分析一下結構:
我們可以分為三塊
第一部分為實時天氣信息欄
代碼如下
// @ts-nocheck
/**
* 該組件為實時天氣預報組件
*
* powered by 堅果
* 2022/7/20
*/
@Entry
@Component
export struct RealtimeWeather{
@State temp: string = "9"
@State text: string = "堅果"
@State isRequestSucceed: boolean = true
build(){
Column() {
Text($r("app.string.city"))
.fontSize(30)
Row() {
Text(this.temp)
.fontSize(100)
Text('℃')
.fontSize(30)
.margin({ top: 10 })
}
.alignItems(VerticalAlign.Top)
.margin({ top: 5 })
Text(this.text)
.fontSize(36)
.margin({ top: 5 })
}.margin({ top: 50 })
}
}
第二部分為
this.WeatherText("日期")
this.WeatherText("天氣")
this.WeatherText("日出")
this.WeatherText("日落")
第三部分為:
Scroll(){
Column(){
ForEach(this.future, (item: WeatherWeekData) = > {
Row() {
this.WeatherText(item.fxDate)
this.WeatherText(item.textDay)
this.WeatherText(item.sunrise)
this.WeatherText(item.sunset)
}.margin({left:10})
}, item = > item.fxDate)
}
}
最后用Column包裹
完整的代碼如下:
Main.ets
// @ts-nocheck
/*
* Copyright (c) 2021 JianGuo Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { WeatherModel, WeatherData, WeatherWeekData, } from '../model/weatherModel';
import { RealtimeWeather } from '../common/RealtimeWeather'
import { getWeekTest } from '../data/get_week_test'
import { getTest } from '../data/get_test'
import prompt from '@system.prompt';
import http from '@ohos.net.http';
@Entry
@Component
struct Main {
aboutToAppear() {
this.getRequest()
this.getWeekRequest()
}
@State realtime: WeatherData = getTest()
@State future: Array< WeatherWeekData > = getWeekTest()
@State isRequestSucceed: boolean = true
@Builder WeatherText(text: string) {
Text(text)
.fontSize(14)
.layoutWeight(1)
.textAlign(TextAlign.Center)
.margin({ top: 10, bottom: 10 })
}
build() {
Column() {
if (this.isRequestSucceed) {
// 當前天氣
RealtimeWeather({ temp: this.realtime.temp, text: this.realtime.text })
Row() {
this.WeatherText("日期")
this.WeatherText("天氣")
this.WeatherText("日出")
this.WeatherText("日落")
}.margin({top:20})
Scroll(){
Column(){
ForEach(this.future, (item: WeatherWeekData) = > {
Row() {
this.WeatherText(item.fxDate)
this.WeatherText(item.textDay)
this.WeatherText(item.sunrise)
this.WeatherText(item.sunset)
}.margin({left:10})
}, item = > item.fxDate)
}
}
Text("數據來自和風天氣")
.fontSize(14)
.margin({ bottom: 30 })
}
}.width("100%").height("100%")
}
// 請求方式:GET 獲取一周天氣預報
getWeekRequest() {
// 每一個httpRequest對應一個http請求任務,不可復用
let httpRequest = http.createHttp()
let url = 'https://devapi.qweather.com/v7/weather/7d?location=101010100&key=48fbadf80bbc43ce853ab9a92408373e'
httpRequest.request(url, (err, data) = > {
if (!err) {
if (data.responseCode == 200) {
console.info('=====data.result=====' + data.result)
// 解析數據
var weatherModel: WeatherModel = JSON.parse(data.result.toString())
// 判斷接口返回碼,0成功
if (weatherModel.code == 200) {
// 設置數據
this.future = weatherModel.daily
this.isRequestSucceed = true;
ForEach(weatherModel.daily, (item: WeatherWeekData) = > {
console.log(console.info('=====data.result+item.fxDate=====' + item.fxDate))
}, item = > item.date)
console.info('=====data.result===' + weatherModel.daily)
} else {
// 接口異常,彈出提示
prompt.showToast({ message: "數據請求失敗" })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: '網絡異常' })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: err.message })
}
})
}
// 請求方式:GET
getRequest() {
// 每一個httpRequest對應一個http請求任務,不可復用
let httpRequest = http.createHttp()
let url = 'https://devapi.qweather.com/v7/weather/now?location=101010100&key=48fbadf80bbc43ce853ab9a92408373e'
httpRequest.request(url, (err, data) = > {
if (!err) {
if (data.responseCode == 200) {
console.info('=====data.result=====' + data.result)
// 解析數據
//this.content= data.result;
// 解析數據
var weatherModel: WeatherModel = JSON.parse(data.result.toString())
// 判斷接口返回碼,0成功
if (weatherModel.code == 200) {
// 設置數據
this.realtime = weatherModel.now
this.isRequestSucceed = true;
console.info('=====data.result===this.content==' + weatherModel.now)
} else {
// 接口異常,彈出提示
prompt.showToast({ message: "數據請求失敗" })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: '網絡異常' })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: err.message })
}
})
}
}
里面用到了網絡請求
網絡請求的步驟
1、聲明網絡請求權限
在entry下的config.json中module字段下配置權限
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
2、支持http明文請求
默認支持https,如果要支持http,在entry下的config.json中deviceConfig字段下配置
"default": {
"network": {
"cleartextTraffic": true
}
}
3、創建HttpRequest
// 導入模塊
import http from '@ohos.net.http';
// 創建HttpRequest對象
let httpRequest = http.createHttp();
4、發起請求
GET請求( 默認為GET請求 )
// 請求方式:GET
getRequest() {
// 每一個httpRequest對應一個http請求任務,不可復用
let httpRequest = http.createHttp()
let url = 'https://devapi.qweather.com/v7/weather/now?location=101010100&key=48fbadf80bbc43ce853ab9a92408373e'
httpRequest.request(url, (err, data) = > {
if (!err) {
if (data.responseCode == 200) {
console.info('=====data.result=====' + data.result)
// 解析數據
//this.content= data.result;
// 解析數據
var weatherModel: WeatherModel = JSON.parse(data.result.toString())
// 判斷接口返回碼,0成功
if (weatherModel.code == 200) {
// 設置數據
this.realtime = weatherModel.now
this.isRequestSucceed = true;
console.info('=====data.result===this.content==' + weatherModel.now)
} else {
// 接口異常,彈出提示
prompt.showToast({ message: "數據請求失敗" })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: '網絡異常' })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: err.message })
}
})}
5、解析數據(簡單示例)
1.網絡請求到的json字符串
export function getTest() {
return [
{
"obsTime": "2022-07-20T09:24+08:00",
"temp": "28",
"feelsLike": "29",
"icon": "101",
"text": "多云",
"wind360": "225",
"windDir": "西南風",
"windScale": "3",
"windSpeed": "17",
"humidity": "71",
"precip": "0.0",
"pressure": "1000",
"vis": "8",
"cloud": "91",
"dew": "21"
},
]
}
2.創建相應的對象
export class WeatherWeekData {
fxDate: string //
sunrise: string //
sunset: string //
moonrise: string //
moonset: string //
moonPhase: string //
moonPhaseIcon: string //
tempMax: string //
tempMin: string //
iconDay: string //
textDay: string
textNight: string //
wind360Day: string //
windDirDay: string //
windScaleDay: string //
windSpeedDay: string //
wind360Night: string //
windDirNight: string //
dew: string //
windScaleNight: string // ,
windSpeedNight: string //
humidity: string //
precip: string //
pressure: string //
vis: string //
cloud: string //
uvIndex: string //
}
實況天氣
目前支持全國4000+個市縣區和海外15萬個城市實時天氣數據,包括實時溫度、體感溫度、風力風向、相對濕度、大氣壓強、降水量、能見度、露點溫度、云量等數據。
)請求URL
// 北京實況天氣
https://devapi.qweather.com/v7/weather/now?location=101010100&key=你的KEY
請求參數
請求參數包括必選和可選參數,如不填寫可選參數將使用其默認值,參數之間使用&
進行分隔。
key
用戶認證key。如何獲取KRY可前往我之前的文章。例如 key=123456789ABC
location
需要查詢地區的LocationID或以英文逗號分隔的經度,緯度坐標十進制,最多支持小數點后兩位),LocationID可通過[城市搜索]服務獲取。例如 location=101010100
或 location=116.41,39.92
返回數據格式
// 北京實況天氣
// https://devapi.qweather.com/v7/weather/now?location=101010100&key=你的KEY
{
"code": "200",
"updateTime": "2020-06-30T22:00+08:00",
"fxLink": "http://hfx.link/2ax1",
"now": {
"obsTime": "2020-06-30T21:40+08:00",
"temp": "24",
"feelsLike": "26",
"icon": "101",
"text": "多云",
"wind360": "123",
"windDir": "東南風",
"windScale": "1",
"windSpeed": "3",
"humidity": "72",
"precip": "0.0",
"pressure": "1003",
"vis": "16",
"cloud": "10",
"dew": "21"
},
"refer": {
"sources": [
"QWeather",
"NMC",
"ECMWF"
],
"license": [
"commercial license"
]
}
}
// 請求方式:GET
getRequest() {
// 每一個httpRequest對應一個http請求任務,不可復用
let httpRequest = http.createHttp()
let url = 'https://devapi.qweather.com/v7/weather/now?location=101010100&key=48fbadf80bbc43ce853ab9a92408373e'
httpRequest.request(url, (err, data) = > {
if (!err) {
if (data.responseCode == 200) {
console.info('=====data.result=====' + data.result)
// 解析數據
//this.content= data.result;
// 解析數據
var weatherModel: WeatherModel = JSON.parse(data.result.toString())
// 判斷接口返回碼,0成功
if (weatherModel.code == 200) {
// 設置數據
this.realtime = weatherModel.now
this.isRequestSucceed = true;
console.info('=====data.result===this.content==' + weatherModel.now)
} else {
// 接口異常,彈出提示
prompt.showToast({ message: "數據請求失敗" })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: '網絡異常' })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: err.message })
}
})
}
七天天氣預報
接口
// 北京7天預報
// https://devapi.qweather.com/v7/weather/7d?location=101010100&key=你的KEY
返回數據
// 北京3天預報
// 商業版 https://api.qweather.com/v7/weather/3d?location=101010100&key=你的KEY
// 開發版 https://devapi.qweather.com/v7/weather/3d?location=101010100&key=你的KEY
{
"code": "200",
"updateTime": "2021-11-15T16:35+08:00",
"fxLink": "http://hfx.link/2ax1",
"daily": [
{
"fxDate": "2021-11-15",
"sunrise": "06:58",
"sunset": "16:59",
"moonrise": "15:16",
"moonset": "03:40",
"moonPhase": "盈凸月",
"moonPhaseIcon": "803",
"tempMax": "12",
"tempMin": "-1",
"iconDay": "101",
"textDay": "多云",
"iconNight": "150",
"textNight": "晴",
"wind360Day": "45",
"windDirDay": "東北風",
"windScaleDay": "1-2",
"windSpeedDay": "3",
"wind360Night": "0",
"windDirNight": "北風",
"windScaleNight": "1-2",
"windSpeedNight": "3",
"humidity": "65",
"precip": "0.0",
"pressure": "1020",
"vis": "25",
"cloud": "4",
"uvIndex": "3"
},
{
"fxDate": "2021-11-16",
"sunrise": "07:00",
"sunset": "16:58",
"moonrise": "15:38",
"moonset": "04:40",
"moonPhase": "盈凸月",
"moonPhaseIcon": "803",
"tempMax": "13",
"tempMin": "0",
"iconDay": "100",
"textDay": "晴",
"iconNight": "101",
"textNight": "多云",
"wind360Day": "225",
"windDirDay": "西南風",
"windScaleDay": "1-2",
"windSpeedDay": "3",
"wind360Night": "225",
"windDirNight": "西南風",
"windScaleNight": "1-2",
"windSpeedNight": "3",
"humidity": "74",
"precip": "0.0",
"pressure": "1016",
"vis": "25",
"cloud": "1",
"uvIndex": "3"
},
{
"fxDate": "2021-11-17",
"sunrise": "07:01",
"sunset": "16:57",
"moonrise": "16:01",
"moonset": "05:41",
"moonPhase": "盈凸月",
"moonPhaseIcon": "803",
"tempMax": "13",
"tempMin": "0",
"iconDay": "100",
"textDay": "晴",
"iconNight": "150",
"textNight": "晴",
"wind360Day": "225",
"windDirDay": "西南風",
"windScaleDay": "1-2",
"windSpeedDay": "3",
"wind360Night": "225",
"windDirNight": "西南風",
"windScaleNight": "1-2",
"windSpeedNight": "3",
"humidity": "56",
"precip": "0.0",
"pressure": "1009",
"vis": "25",
"cloud": "0",
"uvIndex": "3"
}
],
"refer": {
"sources": [
"QWeather",
"NMC",
"ECMWF"
],
"license": [
"commercial license"
]
}
}
代碼
// 請求方式:GET 獲取一周天氣預報
getWeekRequest() {
// 每一個httpRequest對應一個http請求任務,不可復用
let httpRequest = http.createHttp()
let url = 'https://devapi.qweather.com/v7/weather/7d?location=101010100&key=48fbadf80bbc43ce853ab9a92408373e'
httpRequest.request(url, (err, data) = > {
if (!err) {
if (data.responseCode == 200) {
console.info('=====data.result=====' + data.result)
// 解析數據
var weatherModel: WeatherModel = JSON.parse(data.result.toString())
// 判斷接口返回碼,0成功
if (weatherModel.code == 200) {
// 設置數據
this.future = weatherModel.daily
this.isRequestSucceed = true;
ForEach(weatherModel.daily, (item: WeatherWeekData) = > {
console.log(console.info('=====data.result+item.fxDate=====' + item.fxDate))
}, item = > item.date)
console.info('=====data.result===' + weatherModel.daily)
} else {
// 接口異常,彈出提示
prompt.showToast({ message: "數據請求失敗" })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: '網絡異常' })
}
} else {
// 請求失敗,彈出提示
prompt.showToast({ message: err.message })
}
})
}
更多鴻蒙開發知識更新在[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md
]參考學習。
城市搜索
調用接口(Get方式)
請求URL
# 搜索關鍵字beij
// https://geoapi.qweather.com/v2/city/lookup?location=beij&key=你的KEY
location
需要查詢地區的名稱,支持文字、以英文逗號分隔的經度,緯度坐標(十進制,最多支持小數點后兩位)、LocationID或Adcode(僅限中國城市)。例如 location=北京 或 location=116.41,39.92
模糊搜索,當location傳遞的為文字時,支持模糊搜索,即用戶可以只輸入城市名稱一部分進行搜索,最少一個漢字或2個字符,結果將按照相關性和Rank值進行排列,便于開發或用戶進行選擇他們需要查看哪個城市的天氣。例如location=bei,將返回與bei相關性最強的若干結果,包括黎巴嫩的貝魯特和中國的北京市
重名,當location傳遞的為文字時,可能會出現重名的城市,例如陜西省西安市、吉林省遼源市下轄的西安區和黑龍江省牡丹江市下轄的西安區,此時會根據Rank值排序返回所有結果。在這種情況下,可以通過adm參數的方式進一步確定需要查詢的城市或地區,例如location=西安&adm=黑龍江
名詞解釋
Rank值
Rank值是表明一個城市或地區排名的數字,基于多種因素綜合計算而來,例如:人口、面積、GDP、搜索熱度等。取值范圍為1-10,在定位搜索服務中,返回的結果除了關鍵字的相關性以外,也會參考該城市的Rank值。數值越大代表該城市或地區的人口越多、面積更大或更加熱門。例如陜西省西安市的Rank值就要比黑龍江省牡丹江市西安區更高,當使用“西安”作為關鍵字定位的時候,西安市的排名要高于西安區。
LocationID
LocationID或locid,是城市、地區或POI點的ID,一般由數字或字母+數字組成,是一個地點的唯一標識。LocationID可以通過定位搜索服務獲取,中國地區、熱門海外城市、一些POI點的LocationID還可以通過[城市列表]下載。
審核編輯 黃宇
-
接口
+關注
關注
33文章
8611瀏覽量
151237 -
鴻蒙
+關注
關注
57文章
2358瀏覽量
42871
發布評論請先 登錄
相關推薦
評論