暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

在鸿蒙中调用天气预报,学到了!

鸿蒙技术社区 2021-02-05
574

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


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


①在 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 为域名,无需填写协议。


如果请求的服务器域名未配置,是无法请求成功的,且工具不会报错。这里一定记得配置服务器域名。


②在 js 文件中引入 fetch 模块


鸿蒙 js 请求远程服务器的模块为 fetch,在 js 文件的最上方需引入该模块。
import fetch from '@system.fetch';


这里也是有提示的:

③调用 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',
            successres => {
                ......
            }
        });
    }


④处理返回数据需调用 JSON.parse()


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


这里看到虽然 responseType 已设置为 json,但用' . '取其中属性时仍会红线报错,且页面中可以看出并未取到值。


可以猜测此时的 res.data 仍为 string 类型,需调用 JSON.parse() 将其转为 json 类型,随后问题解决。

   onInit() {
        // 加载天气预报
        fetch.fetch({
            url'http://apis.juhe.cn/simpleWeather/query?city=%E5%8D%97%E4%BA%AC&key=e4b4e30c713b6e2a24f4a851258c8457',
            responseType'json',
            successres => {
                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(55);
                }
                this.dailyWeather = dailyWeather;
            }
        });


附上天气预报这一部分的代码:
        <!-- 天气 -->
        <div class="weather">
            <div class="now" if="{{ nowWeather }}">
                <text class="nowPhe">
                    {{ nowWeather.info }}
                </text>
                <text>
                    {{ nowWeather.temperature }}˚C
                </text>
                <div class="nowOther">
                    <text>
                        风力风向: {{ nowWeather.direct }} {{ nowWeather.power }}
                    </text>
                    <text>
                        空气质量: {{ 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-imageurl('./common/weatherbg.jpg');
    background-size: contain;
}
.weather text {
    color#fdfdfd;
}
.now {
    width100%;
    height260px;
    margin-top30px;
    display: flex;
    align-items: center;
    justify-content: space-around;
}
.now>text {
    font-size60px;
}
.nowPhe {
    margin-left20px;
}
.nowOther {
    margin-right20px;
    display: flex;
    flex-direction: column;
    height220px;
    justify-content: space-around;
}
.daily{
    margin-top30px;
    display: flex;
    flex-direction: column;
}
.dailyItem{
    margin0 30px 0 30px;
    height120px;
    border-bottom1px solid #bbbbbb;
    display: flex;
    justify-content: space-between;
    align-items: center;
}


聚合数据天气预报接口:
https://www.juhe.cn/docs/api/id/73


👇扫码关注鸿蒙技术社区👇

专注开源技术,共建鸿蒙生态


“阅读原文”了解更多

文章转载自鸿蒙技术社区,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论