鸿蒙开发微信群,从微信小程序到鸿蒙js开发【03】——fetch获取数据&简单天气预报...

目录:

在微信小程序中,若需要向远程服务器请求数据,使用wx.request接口即可。

6cb548a48763c5c6f49159a8664c6062.png

那么在鸿蒙js开发中,请求远程服务器需要如下几步:

1、在config.json配置网络权限和信任域名。

网络权限的配置是在module.reqPermissions中,配置以下三个权限。工具有提示,还是比较友好的。

"module": {

"reqPermissions": [

{

"name": "ohos.permission.GET_NETWORK_INFO"

},

{

"name": "ohos.permission.SET_NETWORK_INFO"

},

{

"name": "ohos.permission.INTERNET"

}

],

......

信任域名的配置是在deviceConfig中,默认是一个空对象,需配置成如下形式。

"deviceConfig": {

"default": {

"network": {

"usesCleartext": true,

"securityConfig": {

"domainSettings": {

"cleartextPermitted": true,

"domains": [

{

"subdomains": true,

"name": "apis.juhe.cn"

},

{

"subdomains": true,

"name": "api.seniverse.com"

},

{

"subdomains": true,

"name": "v.juhe.cn"

},

{

"subdomains": true,

"name": "api.tianapi.com"

}

]

}

}

}

}

},

在domains数组中,subdomains为是否信任下级域名,name为域名,无需填写协议。如果请求的服务器域名未配置,是无法请求成功的,且工具不会报错。这里一定记得配置服务器域名。

2、在js文件中引入fetch模块。

鸿蒙js请求远程服务器的模块为fetch,在js文件的最上方需引入该模块。

import fetch from '@system.fetch';

这里也是有提示的。

af471c40e5ca2f35cfa84bc760e2c2b2.png

3、调用fetch.fetch发送请求。

来看一下fetch模块的封装,请求的参数,响应的类型,回调函数都可在对象中定义,和wx.request()基本一致。

export default class Fetch {

/**

* Obtains data through the network.

* @param options

*/

static fetch(options: {

/**

* Resource URL.

*/

url: string;

/**

* Request parameter, which can be of the string type or a JSON object.

*/

data?: string | object;

/**

* Request header, which accommodates all attributes of the request.

*/

header?: Object;

/**

* Request methods available: OPTIONS, GET, HEAD, POST, PUT, DELETE and TRACE. The default value is GET.

*/

method?: string;

/**

* The return type can be text, or JSON. By default, the return type is determined based on Content-Type in the header returned by the server.

*/

responseType?: string;

/**

* Called when the network data is obtained successfully.

*/

success?: (data: IFetch) => void;

/**

* Called when the network data fails to be obtained.

*/

fail?: (data: any, code: number) => void;

/**

* Called when the execution is completed.

*/

complete?: () => void;

}): void;

}

比如我在页面初始化执行的方法onInit()中请求聚合数据的天气预报接口,就可以这样写:

onInit() {

// 加载天气预报

fetch.fetch({

url: 'http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=xxxxxxxxx',

responseType: 'json',

success: res => {

......

}

});

}

4、处理返回数据需调用JSON.parse()。

鸿蒙js开发目前调试功能尚不方便,虽有console.log(), console.info()等方法用于打印日志,但实际运行时并未找到日志的打印。所以我只能在视图中划出一小块区域用于调试。

这里看到虽然responseType已设置为json,但用' . '取其中属性时仍会红线报错,且页面中可以看出并未取到值,可以猜测此时的res.data仍为string类型,需调用JSON.parse()将其转为json类型,随后问题解决。

1871e3777bbe7c3a6c842b1832943e5b.png

38d1efa3050ace89e2abf45cb4a1742b.png

onInit() {

// 加载天气预报

fetch.fetch({

url: 'http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=e4b4e30c713b6e2a24f4a851258c8457',

responseType: 'json',

success: res => {

console.info(JSON.stringify(res.data)); //并未打印日志

let data = JSON.parse(res.data); //必须要加上

this.nowWeather = data.result.realtime;

let dailyWeather = data.result.future;

for(let i in dailyWeather) {

dailyWeather[i].date = dailyWeather[i].date.substr(5, 5);

}

this.dailyWeather = dailyWeather;

}

});

40db81efc3accf8f55a2723592e39866.png

附上天气预报这一部分的代码:

{{ nowWeather.info }}

{{ nowWeather.temperature }}˚C

风力风向: {{ nowWeather.direct }} {{ nowWeather.power }}

空气质量: {{ nowWeather.aqi }}

{{ $item.date }}

{{ $item.weather }}

{{ $item.temperature }}

/*天气*/

.weather {

background-image: url('./common/weatherbg.jpg');

background-size: contain;

}

.weather text {

color: #fdfdfd;

}

.now {

width: 100%;

height: 260px;

margin-top: 30px;

display: flex;

align-items: center;

justify-content: space-around;

}

.now>text {

font-size: 60px;

}

.nowPhe {

margin-left: 20px;

}

.nowOther {

margin-right: 20px;

display: flex;

flex-direction: column;

height: 220px;

justify-content: space-around;

}

.daily{

margin-top: 30px;

display: flex;

flex-direction: column;

}

.dailyItem{

margin: 0 30px 0 30px;

height: 120px;

border-bottom: 1px solid #bbbbbb;

display: flex;

justify-content: space-between;

align-items: center;

}

作者:Chris.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值