從微信小程序到鴻蒙JS開發(fā)【03】-fetch獲取數(shù)據(jù)&簡(jiǎn)單天氣預(yù)報(bào)
想了解更多內(nèi)容,請(qǐng)?jiān)L問(wèn):
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
https://harmonyos.51cto.com/#zz
在微信小程序中,若需要向遠(yuǎn)程服務(wù)器請(qǐng)求數(shù)據(jù),使用wx.request接口即可。

那么在鴻蒙js開發(fā)中,請(qǐng)求遠(yuǎn)程服務(wù)器需要如下幾步:
1、在config.json配置網(wǎng)絡(luò)權(quán)限和信任域名。
網(wǎng)絡(luò)權(quán)限的配置是在module.reqPermissions中,配置以下三個(gè)權(quán)限。工具有提示,還是比較友好的。
- "module": {
- "reqPermissions": [
- {
- "name": "ohos.permission.GET_NETWORK_INFO"
- },
- {
- "name": "ohos.permission.SET_NETWORK_INFO"
- },
- {
- "name": "ohos.permission.INTERNET"
- }
- ],
- ......
信任域名的配置是在deviceConfig中,默認(rèn)是一個(gè)空對(duì)象,需配置成如下形式。
- "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數(shù)組中,subdomains為是否信任下級(jí)域名,name為域名,無(wú)需填寫協(xié)議。如果請(qǐng)求的服務(wù)器域名未配置,是無(wú)法請(qǐng)求成功的,且工具不會(huì)報(bào)錯(cuò)。這里一定記得配置服務(wù)器域名。
2、在js文件中引入fetch模塊。
鴻蒙js請(qǐng)求遠(yuǎn)程服務(wù)器的模塊為fetch,在js文件的最上方需引入該模塊。
- import fetch from '@system.fetch';
這里也是有提示的。

3、調(diào)用fetch.fetch發(fā)送請(qǐng)求。
來(lái)看一下fetch模塊的封裝,請(qǐng)求的參數(shù),響應(yīng)的類型,回調(diào)函數(shù)都可在對(duì)象中定義,和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;
- }
比如我在頁(yè)面初始化執(zhí)行的方法onInit()中請(qǐng)求聚合數(shù)據(jù)的天氣預(yù)報(bào)接口,就可以這樣寫:
- onInit() {
- // 加載天氣預(yù)報(bào)
- fetch.fetch({
- url: 'http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=xxxxxxxxx',
- responseType: 'json',
- success: res => {
- ......
- }
- });
- }
4、處理返回?cái)?shù)據(jù)需調(diào)用JSON.parse()。
鴻蒙js開發(fā)目前調(diào)試功能尚不方便,雖有console.log(), console.info()等方法用于打印日志,但實(shí)際運(yùn)行時(shí)并未找到日志的打印。所以我只能在視圖中劃出一小塊區(qū)域用于調(diào)試。
這里看到雖然responseType已設(shè)置為json,但用' . '取其中屬性時(shí)仍會(huì)紅線報(bào)錯(cuò),且頁(yè)面中可以看出并未取到值,可以猜測(cè)此時(shí)的res.data仍為string類型,需調(diào)用JSON.parse()將其轉(zhuǎn)為json類型,隨后問(wèn)題解決。

- onInit() {
- // 加載天氣預(yù)報(bào)
- 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;
- }
- });
附上天氣預(yù)報(bào)這一部分的代碼:
- <!-- 天氣 -->
- <div class="weather">
- <div class="now" if="{{ nowWeather }}">
- <text class="nowPhe">
- {{ nowWeather.info }}
- </text>
- <text>
- {{ nowWeather.temperature }}˚C
- </text>
- <div class="nowOther">
- <text>
- 風(fēng)力風(fēng)向: {{ nowWeather.direct }} {{ nowWeather.power }}
- </text>
- <text>
- 空氣質(zhì)量: {{ nowWeather.aqi }}
- </text>
- </div>
- </div>
- <div class="daily" if="{{ dailyWeather }}">
- <block for="{{ dailyWeather }}">
- <div class="dailyItem">
- <text>
- {{ $item.date }}
- </text>
- <text>
- {{ $item.weather }}
- </text>
- <text>
- {{ $item.temperature }}
- </text>
- </div>
- </block>
- </div>
- </div>
- <!-- 天氣end -->
- /*天氣*/
- .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;
- }
想了解更多內(nèi)容,請(qǐng)?jiān)L問(wèn):
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
https://harmonyos.51cto.com/#zz