“本学期学习了鸿蒙开发课程,想通过一个小项目检验一下自己所学,下面把该项目总结一下,希望对学习鸿蒙开发的小伙伴提供一些参考。”
如:“学习鸿蒙正其时,作为中工的一名学生,现在总结一下希望为同砚们后续学习提供参考。”
一.功能实现总结
这个鸿蒙气候应用通过直观的界面设计,整合多种功能,为用户提供全面的气候服务。以下是具体实现的功能细节:
1. 及时气候信息展示
- 当前位置:应用通过定位功能,表现用户所在位置(如“河南省·临颍”),提供本地化的气候预报。
- 当前气候状态:
- 及时温度(如 5°C),以夺目标大字体表现。
- 当前气候状态(如“雾”)及当天的最高温度和最低温度(如 8°C / 1°C)。
- 氛围质量指数:例如表现氛围状态为“轻度污染”,提示用户氛围质量状态。
- 降水环境:如“暂无降水”,表现短时间内无雨雪气候。
2. 短期气候预报
- 提供将来几天(如3天)的气候信息,包括:
- 天天的气候状态(如晴、雾)。
- 温度范围(最高温度/最低温度,如8°C / 1°C)。
- 氛围质量等级(如“优”)。
- 配合简便的气候图标,让用户快速把握将来气候厘革趋势。
3. 24小时气候猜测
- 针对当日气候,提供逐小时的温度、湿度、风速、降水概率等数据,帮助用户更精准地规划活动。
4. 高级景象信息
- 湿度:及时湿度值(如96%)。
- 体感温度:表现比实际温度更靠近人体感知的温度。
- 紫外线强度:如“1级”,提示日晒强度适中。
- 气压:提供及时气压值(如1017 hPa),供需要更精细景象信息的用户参考。
- 风速与风向:如“南风1级”,通过图形化展示风的方向与强度。
5. 长期气候预报
- 提供一个“查看近7天气候”的按钮,支持更具体的长期气候查询,便于用户提前做好预备。
界面设计与用户体验
- 简便高效:
- 使用极简风格,重点信息(如温度、气候状态)以大字体和夺目标结构突出,信息分类清晰。
- 图标搭配文字,便于快速理解气候状态。
- 高交互性:
- 通过按钮设计(如“查看近7天气候”),引导用户探索更多功能。
- 多屏信息整合,及时数据与短期预报联合,满足多样化需求。
- 贴心功能:
- 氛围质量、湿度、紫外线等指标提供全面的数据参考,覆盖多种使用场景,如穿衣、出行等。
适用场景
- 一样平常出行:查看及时气候、氛围质量和降水信息,便于出行安排。
- 活动计划:通过短期或长期气候预报规划外出活动。
- 康健防护:参考湿度、紫外线强度和氛围质量,及时做好防护措施。
二. 告急代码实现
1. 告急页面项目代码展示
实现代码项目截图
- import log from '../../common/log'
- import { promptAction } from '@kit.ArkUI'
- import {
- ForecastWeatherDayResult,
- ForecastWeatherHourResult,
- NowAirResult,
- RealWeatherResult
- } from '../../network/type'
- import { distributedKVStore } from '@kit.ArkData'
- import {
- checkDataValidate,
- fetchAndCachedForecast24HourWeather,
- fetchAndCachedForecast7DayWeather,
- fetchAndCachedNowAirData,
- fetchAndCachedRealWeatherData,
- getWeatherKvStore
- } from '../../utils/WeatherKvStore'
- import * as constants from '../../common/constants'
- import { RealTemperature } from './RealTemperature'
- import { Fetch3dayWeather } from './Fetch3dayWeather'
- import { DayTrendPageNavParam } from '../DayTrend/DayTrendPage'
- import { Forecast24HourWetherComponent } from './Forecast24Hour/Forecast24HourWeather'
- import { RealTimeWeather } from './RealTimeWeather'
- import { BusinessError } from '@kit.BasicServicesKit'
- export interface CityWeatherOptions {
- location: string,
- }
- interface RealTemperatureVO {
- curTemp: number
- weatherDesc: string
- airQualityIndex: number
- airQualityDesc: string,
- rain: number,
- highestTemp: number,
- lowestTemp: number,
- }
- function transformRealTemperatureVO(
- realWeatherData: RealWeatherResult,
- airData: NowAirResult,
- forecastData: ForecastWeatherDayResult
- ) {
- const vo: RealTemperatureVO = {
- curTemp: parseInt(realWeatherData.now.temp),
- weatherDesc: realWeatherData.now.text,
- airQualityIndex: parseInt(airData.now.aqi),
- airQualityDesc: airData.now.category,
- rain: parseFloat(realWeatherData.now.precip),
- highestTemp: parseInt(forecastData.daily[0].tempMax),
- lowestTemp: parseInt(forecastData.daily[0].tempMin),
- }
- return vo
- }
- /**
- * 城市天气的主要组件
- * 主要逻辑:
- * 1. 从本地缓存中获取历史数据,使用该数据,如果超过过期时间,进行更新~
- * 2. 下拉刷新操作
- * */
- @Component
- export struct CityWeather {
- @Consume("pageStack") pathStack: NavPathStack
- @Prop options: CityWeatherOptions
- /** 刷新状态 */
- @State
- private refreshing: boolean = false
- /** 当前刷新完成数 */
- @State
- private refreshingCounter: number = 0
- @State
- private refreshingText: string = '刷新中...'
- private kvStore?: distributedKVStore.DeviceKVStore = undefined
- /** 实时天气数据 */
- @State
- @Watch('updateRealTemperatureVOData')
- private realWeatherData?: RealWeatherResult = undefined
- /** 7天预测数据 */
- @State
- @Watch('updateRealTemperatureVOData')
- private forecastDayWeatherData?: ForecastWeatherDayResult = undefined
- /** 24小时预测数据 */
- @State
- private forecastHourWeatherData?: ForecastWeatherHourResult = undefined
- /** 空气数据 */
- @State
- @Watch('updateRealTemperatureVOData')
- private airQualityData?: NowAirResult = undefined
- /** 实时天气数据VO */
- @State
- private realTemperatureVOData?: RealTemperatureVO = undefined
- private updateRealTemperatureVOData(pro: string) {
- if (pro === 'realWeatherData' || pro === 'forecastDayWeatherData' || pro === 'airQualityData') {
- if (this.realWeatherData && this.forecastDayWeatherData && this.airQualityData) {
- this.realTemperatureVOData = transformRealTemperatureVO(this.realWeatherData, this.airQualityData, this.forecastDayWeatherData)
- }
- }
- }
- /**
- * 开始刷新操作
- * */
- private startRefreshing() {
- this.refreshing = true
- this.refreshingCounter++
- this.refreshingText = "刷新中..."
- }
- /**
- * 刷新完毕操作
- * */
- private completedRefreshing() {
- this.refreshingCounter--;
- if (this.refreshingCounter === 0) {
- this.refreshingText = "刷新成功!"
- setTimeout(() => {
- this.refreshing = false
- }, 500)
- }
- }
- /**
- * 刷新实时天气数据(实时温度、空气数据、7天数据)
- * */
- private async fetchAndCachedRealWeatherData() {
- this.startRefreshing()
- try {
- this.realWeatherData = await fetchAndCachedRealWeatherData(this.options.location, this.kvStore!)
- this.airQualityData = await fetchAndCachedNowAirData(this.options.location, this.kvStore!)
- this.forecastDayWeatherData = await fetchAndCachedForecast7DayWeather(this.options.location, this.kvStore!)
- // 更新状态变量
- this.realTemperatureVOData =
- transformRealTemperatureVO(this.realWeatherData, this.airQualityData, this.forecastDayWeatherData)
- } catch (error) {
- promptAction.showToast({
- message: '网络错误!请重新刷新!'
- })
- log.error('fetchRealWeatherData', error)
- } finally {
- this.completedRefreshing()
- }
- }
- private fetchAndCachedRealAirData() {
- console.log('fetchAndCachedRealAirData kv store', this.kvStore)
- this.startRefreshing()
- fetchAndCachedNowAirData(this.options!.location, this.kvStore!)
- .then((res) => {
- this.airQualityData = res
- })
- .catch((err: Error) => {
- log.error('fetchAndCachedAirData Failed!', JSON.stringify(err))
- promptAction.showToast({
- message: '获取数据失败,请检查网络!'
- })
- })
- .finally(() => {
- this.completedRefreshing()
- })
- }
- /**
- * 获取未来7天的数据
- * */
- private fetchAndCachedForecastDayWeatherData() {
- this.startRefreshing()
- fetchAndCachedForecast7DayWeather(this.options!.location, this.kvStore!)
- .then((res) => {
- this.forecastDayWeatherData = res
- })
- .catch((err: Error) => {
- log.error("fetchForecastWeatherDayData failed", err)
- promptAction.showToast({
- message: '获取数据失败,请检查网络!'
- })
- })
- .finally(() => {
- this.completedRefreshing()
- })
- }
- /**
- * 获取未来24小时的数据
- * */
- private fetchAndCachedForecastHourWeatherData() {
- this.startRefreshing()
- console.log('fetchForecastHourWeatherData kv store', this.kvStore)
- fetchAndCachedForecast24HourWeather(this.options!.location, this.kvStore!)
- .then((res) => {
- this.forecastHourWeatherData = res
- })
- .catch((err: Error) => {
- log.error("fetchForecastHourWeatherData failed", err)
- promptAction.showToast({
- message: '获取数据失败,请检查网络!'
- })
- })
- .finally(() => {
- this.completedRefreshing()
- })
- }
- /** 刷新所有天气数据 */
- private refreshAllWeatherData() {
- this.loadDataFromKvStore()
- }
- /**
- * 从本地读取缓存的数据,如果没有或者过期,则执行刷新操作
- * */
- private async loadDataFromKvStore() {
- // 当前实时天气
- this.startRefreshing()
- checkDataValidate<RealWeatherResult>(
- this.kvStore!,
- constants.getRealWeatherDataKey(this.options.location),
- 5 * 60 * 1000,
- )
- .then((res) => {
- console.log(`checkDataValidate<RealWeatherResult> need refresh: ${res === undefined}`)
- if (res) {
- this.realWeatherData = res
- } else {
- this.fetchAndCachedRealWeatherData()
- }
- })
- .catch((err: BusinessError) => {
- console.error(`checkDataValidate<RealWeatherResult> failed: (${err.code}) ${err.message}`)
- })
- .finally(() => {
- this.completedRefreshing()
- })
- // 当前空气质量数据
- this.startRefreshing()
- checkDataValidate<NowAirResult>(
- this.kvStore!,
- constants.getRealWeatherAirDataKey(this.options.location),
- 5 * 60 * 1000,
- )
- .then((res) => {
- console.log(`checkDataValidate<NowAirResult> need refresh: ${res === undefined}`)
- if (res) {
- this.airQualityData = res
- } else {
- this.fetchAndCachedRealAirData()
- }
- })
- .catch((err: BusinessError) => {
- console.error(`checkDataValidate<NowAirResult> failed: (${err.code}) ${err.message}`)
- })
- .finally(() => {
- this.completedRefreshing()
- })
- // 当前7天天气数据
- this.startRefreshing()
- checkDataValidate<ForecastWeatherDayResult>(
- this.kvStore!,
- constants.getForecastWeatherDayDataKey(this.options.location),
- 10 * 60 * 1000,
- )
- .then((res) => {
- console.log(`checkDataValidate<ForecastWeatherDayResult> need refresh: ${res === undefined}`)
- if (res) {
- this.forecastDayWeatherData = res
- } else {
- this.fetchAndCachedForecastDayWeatherData()
- }
- })
- .catch((err: BusinessError) => {
- console.error(`checkDataValidate<ForecastWeatherDayResult> failed: (${err.code}) ${err.message}`)
- })
- .finally(() => {
- this.completedRefreshing()
- })
- this.startRefreshing()
- checkDataValidate<ForecastWeatherHourResult>(
- this.kvStore!,
- constants.getForecastWeatherHourDataKey(this.options.location),
- 10 * 60 * 1000,
- )
- .then((res) => {
- console.log(`checkDataValidate<ForecastWeatherHourResult> need refresh: ${res === undefined}`)
- if (res) {
- this.forecastHourWeatherData = res
- } else {
- this.fetchAndCachedForecastHourWeatherData()
- }
- })
- .catch((err: BusinessError) => {
- console.error(`checkDataValidate<ForecastWeatherHourResult> failed: (${err.code}) ${err.message}`)
- })
- .finally(() => {
- this.completedRefreshing()
- })
- }
- private navigateToTrendPage() {
- const data: DayTrendPageNavParam = {
- shouldShowNavigation: false,
- added: true,
- locationID: this.options.location,
- cityName: '',
- data: this.forecastDayWeatherData!
- }
- this.pathStack.pushDestinationByName("day_trend", data, true)
- }
- aboutToAppear(): void {
- // 获取本地数据库
- getWeatherKvStore(getContext(this))
- .then((store) => {
- this.kvStore = store
- this.loadDataFromKvStore()
- })
- }
- build() {
- Refresh({ refreshing: $$this.refreshing, promptText: this.refreshingText }) {
- Scroll() {
- Column({ space: 24 }) {
- if (this.realTemperatureVOData) {
- Column({ space: 24 }) {
- RealTemperature({
- options: {
- curTemp: this.realTemperatureVOData!.curTemp,
- weatherText: this.realTemperatureVOData!.weatherDesc,
- highTemp: this.realTemperatureVOData!.highestTemp,
- lowTemp: this.realTemperatureVOData!.lowestTemp,
- rain: this.realTemperatureVOData!.rain,
- airQualityIndex: this.realTemperatureVOData!.airQualityIndex,
- airQualityDesc: this.realTemperatureVOData!.airQualityDesc,
- }
- })
- Fetch3dayWeather({
- options: {
- dataList: this.forecastDayWeatherData!.daily,
- onNavigate: () => {
- this.navigateToTrendPage()
- }
- }
- })
- }
- .alignItems(HorizontalAlign.Center)
- .justifyContent(FlexAlign.SpaceBetween) // 保证分开两部分
- .width('100%')
- .height('100%')
- Column({ space: 24 }) {
- Forecast24HourWetherComponent({
- dataList: this.forecastHourWeatherData?.hourly
- })
- .height(300)
- RealTimeWeather({
- options: {
- sunset: this.forecastDayWeatherData!.daily[0].sunset ?? '',
- sunrise: this.forecastDayWeatherData!.daily[0].sunrise ?? '',
- moonrise: this.forecastDayWeatherData!.daily[0].moonrise ?? '',
- moonset: this.forecastDayWeatherData!.daily[0].moonset ?? '',
- uvIndex: this.forecastDayWeatherData!.daily[0].uvIndex,
- realData: this.realWeatherData!
- }
- })
- }
- }
- }
- .width("100%")
- .padding({ left: 16, right: 16 })
- }
- .height('100%')
- .width('100%')
- .scrollable(ScrollDirection.Vertical)
- .scrollBar(BarState.Off)
- }
- .height('100%')
- .width('100%')
- .onRefreshing(() => {
- this.refreshAllWeatherData()
- })
- }
- }
复制代码 这段代码实现了城市气候数据展示与交互功能的组件。通过与气候相干的 API 集成,组件能及时表现城市气候信息并支持革新操作,同时通过缓存优化了性能。
2. 告急对象创建与模块代码展示
- import { RealWeatherResult } from '../network/type'
- export const RealWeatherResultList: RealWeatherResult[] = [
- {
- code: '300',
- /**
- * 最近更新时间
- * */
- updateTime: new Date(),
- /** 当前数据的响应式页面 */
- fxLink: 'string',
- now: {
- /** 数据观测时间 */
- obsTime: "string",
- /** 温度,默认单位摄氏度 */
- temp: '30',
- /** 体感温度 */
- feelsLike: "string",
- /** 图标代码 */
- icon: 'string',
- /** 天气描述 */
- text: 'string',
- /** 风向360角 */
- wind360: 'string',
- /** 风向 */
- windDir: 'string',
- /** 风力等级 */
- windScale: 'string',
- /** 风速 km/h */
- windSpeed: 'string',
- /** 湿度 % */
- humidity: 'string',
- /** 当前小时累计降水量,mm */
- precip: 'string',
- /** 大气压强,百帕 */
- pressure: 'string',
- /** 能见度, km */
- vis: 'string',
- },
- refer: {
- sources: [],
- license: []
- }
- }
复制代码- export class LocationBean {
- /** 城市名称 */
- name: string;
- /** 城市id, location要用的 */
- id: string;
- /** 城市经度 */
- lat: string;
- /** 城市纬度 */
- lon: string;
- /** 上级行政区划名称 */
- adm2: string;
- /** 所属一级形成区域 */
- adm1: string;
- /** 所属国家名称 */
- country: string;
- /** 所处时区 */
- tz: string;
- /** UTC事件偏移的小时数 */
- utcOffset: string;
- /** 是否处于夏令时,1是0否 */
- isDst: string;
- /** 城市属性 */
- type: string;
- /** 地区评分 */
- rank: string;
- /** 该城市的天气预报网页链接 */
- fxLink: string;
- constructor(
- name: string,
- id: string,
- lat: string,
- lon: string,
- adm2: string,
- adm1: string,
- country: string,
- tz: string,
- utcOffset: string,
- isDst: string,
- type: string,
- rank: string,
- fxLink: string
- ) {
- this.name = name;
- this.id = id;
- this.lat = lat;
- this.lon = lon;
- this.adm2 = adm2;
- this.adm1 = adm1;
- this.country = country;
- this.tz = tz;
- this.utcOffset = utcOffset;
- this.isDst = isDst;
- this.type = type;
- this.rank = rank;
- this.fxLink = fxLink;
- }
- }
复制代码- export interface CityModel {
- /** 城市名字 */
- cityName: string,
- /** id */
- locationID: string,
- /** 所属省份 */
- provinceName: string,
- /** 经度 */
- longitude: number,
- /** 纬度 */
- latitude: number,
- /** 定位城市 */
- isLocationCity: boolean,
- /**
- * 创建时间
- * */
- createTimestamp: number,
- }
- export interface RealWeatherData {
- /** 数据观测时间 */
- obsTime: string,
- /** 温度,默认单位摄氏度 */
- temp: string,
- /** 体感温度 */
- feelsLike: string,
- /** 图标代码 */
- icon: string,
- /** 天气描述 */
- text: string,
- /** 风向360角 */
- wind360: string,
- /** 风向 */
- windDir: string,
- /** 风力等级 */
- windScale: string,
- /** 风速 km/h */
- windSpeed: string,
- /** 湿度 % */
- humidity: string,
- /** 当前小时累计降水量,mm */
- precip: string,
- /** 大气压强,百帕 */
- pressure: string,
- /** 能见度, km */
- vis: string,
- /** 云量,百分比,可能为空 */
- cloud?: string,
- /** 露点温度,可能为空 */
- dew?: string,
- }
复制代码 3. 气候数据的获取功能告急代码展示
- import { API_KEY } from '../common/config'
- import { request } from '../common/request'
- import {
- ForecastWeatherDayResult,
- ForecastWeatherHourResult,
- LocationParam,
- LocationResult,
- NowAirResult,
- RealWeatherResult,
- WeatherIndexResult,
- WeatherParam
- } from './type'
- /**
- * 通过经纬度查询当前城市信息
- * @param {string} lon 经度,十进制最多两位小数
- * @param {string} lat 纬度,十进制最多两位小数
- * */
- export function fetchCityByLatitudeAndLongitude(lon: number, lat: number): Promise<LocationResult> {
- return request<LocationParam, LocationResult>('https://geoapi.qweather.com/v2/city/lookup', {
- useBaseUrl: false,
- param: {
- key: API_KEY,
- location: `${lon.toFixed(2)},${lat.toFixed(2)}`,
- range: 'cn',
- number: 20,
- }
- })
- }
- /**
- * 获取到实时天气
- * */
- export function fetchRealWeather(
- location: string,
- ): Promise<RealWeatherResult> {
- return request<WeatherParam, RealWeatherResult>('/v7/weather/now', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
- /**
- * 获取未来3天天气预报
- * */
- export function fetchForecast3DayWeather(
- location: string
- ): Promise<ForecastWeatherDayResult> {
- return request<WeatherParam, ForecastWeatherDayResult>('/v7/weather/3d', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
- /**
- * 获取未来7天天气预报
- * */
- export function fetchForecast7DayWeather(
- location: string
- ): Promise<ForecastWeatherDayResult> {
- return request<WeatherParam, ForecastWeatherDayResult>('/v7/weather/7d', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
- /**
- * 获取未来24小时天气预报
- * */
- export function fetchForecast24HourWeather(
- location: string
- ): Promise<ForecastWeatherHourResult> {
- return request<WeatherParam, ForecastWeatherHourResult>('/v7/weather/24h', {
- useBaseUrl: false,
- param: {
- key: API_KEY,
- location: location
- },
- })
- }
- /*
- * 根据关键字获取城市信息
- * */
- export function fetchCityInfoByKeyWord(
- keyword: string
- ): Promise<LocationResult> {
- return request<LocationParam, LocationResult>('https://geoapi.qweather.com/v2/city/lookup', {
- param: {
- key: API_KEY,
- location: keyword
- }
- })
- }
- /**
- * 获取空气质量数据
- * */
- export function fetchNowAir(
- location: string,
- ): Promise<NowAirResult> {
- return request<WeatherParam, NowAirResult>('/v7/air/now', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
- /**
- * 获取天气指数
- * */
- export function fetchWeatherIndices(
- location: string,
- ): Promise<WeatherIndexResult> {
- return request<WeatherParam, WeatherIndexResult>('/v7/indices/1d', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
复制代码 该代码文件是项目标核心数据交互模块,完成了:
- 及时气候与猜测数据的获取:涵盖从当前到将来 7 天的气候数据。
- 氛围质量与生活指数的查询:提供额外的环境和生活信息。
- 城市定位与查询:支持自动定位和关键字搜索。
通过 API 的分层封装,代码清晰易扩展,便于后续功能升级和维护。
4. 搜索功能组件代码实现告急展示
- import { CityMangerModel2, CityWeatherVO } from '../../model/CityManagerModel2'
- import { CityModel } from '../../model/CityModel'
- import { fetchCityInfoByKeyWord } from '../../network/api'
- import { Location, LocationResult } from '../../network/type'
- import { SearchResult } from './SearchResult'
- import { CityManager } from './CityManager'
- /*
- * 搜索
- * */
- @Component
- export struct SearchLink {
- result?: LocationResult
- @State locations: Location[] = []
- @State
- isShow: boolean = false
- @Link
- dataList: CityMangerModel2[]
- @Link
- tureDataList: CityWeatherVO[]
- @Link citiesInfo: CityModel[]
- private searchDebounceId = -1
- /**
- * 搜索结果变化触发api搜索
- * */
- private searchValueChange(value: string) {
- if (value) {
- if (this.searchDebounceId != -1) {
- clearTimeout(this.searchDebounceId)
- }
- this.searchDebounceId = setTimeout(() => {
- fetchCityInfoByKeyWord(value).then(value1 => {
- this.result = value1
- this.locations = value1.location
- this.isShow = true
- })
- }, 300)
- } else {
- clearTimeout(this.searchDebounceId)
- this.searchDebounceId = -1
- this.isShow = false
- }
- }
- build() {
- Column() {
- //搜索框
- Row() {
- Search({ placeholder: '搜索位置' })
- .width('100%')
- .onChange(value => {
- this.searchValueChange(value)
- })
- }
- //搜索结果列表
- Stack() {
- CityManager({ dataList: this.dataList, trueDataList: this.tureDataList, citiesInfo: this.citiesInfo })
- if (this.isShow) {
- SearchResult({
- locations: this.locations,
- dataList: this.dataList,
- tureDataList: this.tureDataList,
- citiesInfo: this.citiesInfo
- })
- }
- }
- }
- .height('100%')
- .padding({ left: 20, right: 20, top: 20 })
- .alignItems(HorizontalAlign.Center)
- }
- }
复制代码 这段代码实现了一个位置搜索功能的组件,用于根据用户输入的关键字搜索城市信息,并将结果展示出来。用户可以通过搜索框输入关键字,触发搜索 API 获取城市列表,并在界面中动态表现搜索结果。
5. 气候和城市相干的 API 请求功能实现告急代码展示
- import { API_KEY } from '../common/config'
- import { request } from '../common/request'
- import {
- ForecastWeatherDayResult,
- ForecastWeatherHourResult,
- LocationParam,
- LocationResult,
- NowAirResult,
- RealWeatherResult,
- WeatherIndexResult,
- WeatherParam
- } from './type'
- /**
- * 通过经纬度查询当前城市信息
- * @param {string} lon 经度,十进制最多两位小数
- * @param {string} lat 纬度,十进制最多两位小数
- * */
- export function fetchCityByLatitudeAndLongitude(lon: number, lat: number): Promise<LocationResult> {
- return request<LocationParam, LocationResult>('https://geoapi.qweather.com/v2/city/lookup', {
- useBaseUrl: false,
- param: {
- key: API_KEY,
- location: ${lon.toFixed(2)},${lat.toFixed(2)},
- range: 'cn',
- number: 20,
- }
- })
- }
- /**
- * 获取到实时天气
- * */
- export function fetchRealWeather(
- location: string,
- ): Promise<RealWeatherResult> {
- return request<WeatherParam, RealWeatherResult>('/v7/weather/now', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
- /**
- * 获取未来3天天气预报
- * */
- export function fetchForecast3DayWeather(
- location: string
- ): Promise<ForecastWeatherDayResult> {
- return request<WeatherParam, ForecastWeatherDayResult>('/v7/weather/3d', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
- /**
- * 获取未来7天天气预报
- * */
- export function fetchForecast7DayWeather(
- location: string
- ): Promise<ForecastWeatherDayResult> {
- return request<WeatherParam, ForecastWeatherDayResult>('/v7/weather/7d', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
- /**
- * 获取未来24小时天气预报
- * */
- export function fetchForecast24HourWeather(
- location: string
- ): Promise<ForecastWeatherHourResult> {
- return request<WeatherParam, ForecastWeatherHourResult>('/v7/weather/24h', {
- useBaseUrl: false,
- param: {
- key: API_KEY,
- location: location
- },
- })
- }
- /*
- * 根据关键字获取城市信息
- * */
- export function fetchCityInfoByKeyWord(
- keyword: string
- ): Promise<LocationResult> {
- return request<LocationParam, LocationResult>('https://geoapi.qweather.com/v2/city/lookup', {
- param: {
- key: API_KEY,
- location: keyword
- }
- })
- }
- /**
- * 获取空气质量数据
- * */
- export function fetchNowAir(
- location: string,
- ): Promise<NowAirResult> {
- return request<WeatherParam, NowAirResult>('/v7/air/now', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
- /**
- * 获取天气指数
- * */
- export function fetchWeatherIndices(
- location: string,
- ): Promise<WeatherIndexResult> {
- return request<WeatherParam, WeatherIndexResult>('/v7/indices/1d', {
- param: {
- key: API_KEY,
- location: location
- }
- })
- }
复制代码 这段代码实现了与气候和城市相干的 API 请求功能,告急用于获取及时气候、气候预报、城市信息、氛围质量等数据。每个函数都是基于 fetch 函数封装的,用于向景象 API 发送请求并获取相应数据
三.项目实现截图展示
四.项目不足与经验总结
项目设计不足
- 错误处置惩罚机制不同一:不同的请求有不同的错误处置惩罚方式,缺少同一的管理。
- 数据缓存策略不美满:缓存逾期时间与革新机制不够机动,可能导致数据滞后。
- 网络请求与组件耦合:网络请求和 UI 组件耦合过深,应该解耦。
- 过度依赖外部 API:对第三方 API 依赖过高,缺少容错机制和备用方案。
- UI 设计与用户体验欠缺:UI 交互和细节优化不足,加载提示和数据展示有待改进。
- 气候数据展示层次不清晰:展示的气候数据缺乏优先级和层次感。
- 缺少单元测试与自动化测试:缺少美满的单元测试和自动化测试,难以及时发现问题。
经验总结
- 模块化设计:功能模块化提高代码可维护性和可扩展性。
- 合理利用数据缓存:优化缓存机制,淘汰网络请求,提高用户体验。
- UI 交互优化:通过动态结果和反馈提升用户体验。
- 提前规划错误处置惩罚:同一的错误处置惩罚机制提升代码可靠性。
- 第三方 API 备选方案:避免过度依赖单一 API,增长容错机制。
- 清晰的数据结构界说:明确数据格式和结构,保证一致性。
- 可扩展性:设计时考虑将来功能扩展,保持机动性。
参考与告急鉴戒网址:GitHub - YeMengLiChou/LuckWeather-HarmonyApp: 鸿蒙课设开发——晴气候App
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |