用天行数据API接口开发一个新闻微信小程序

时间:2019-03-07 13:18:17

天行数据提供了近30个新闻图文类API接口,给开发者调用。以下小项目,演示如何在开发微信或百度小程序时,调用这些数据。小程序中可以左右滑动切换栏目分类,上拉、下拉刷新数据。项目使用部分网上开源的项目代码,前端使用了weui.wxss组件。在文末有完整项目代码可下载,导入到微信web开发者工具中后修改util.js文件中的key为你在天行数据中得到的apikey即可看到效果。如果需要在百度智能小程序中使用,由于项目中并没有微信专有的特殊API,理论上直接在百度开发者工具中转换即可,故没有单独作出兼容性调整,如有问题可直接留言。具体方法可参考《百度智能小程序的开发笔记》这篇文章,注意别忘了在对应的平台添加安全域名api.tianapi.com。


用天行数据API接口开发一个新闻微信小程序


1,在项目目录utils下的utils.js文件,声明几个会经常使用的变量。天行数据的API请求地址、密匙以及新闻类目。

var txapi_base_url = "https://api.tianapi.com";  //天行数据接口域名
var txapi_key = "";  //请填写你在天行数据www.tianapi.com获得apikey

var NewsTypeList = [
  {
    NewsTypeId: 7,    //新闻类目ID
    TypeName: '国内',
  },
  {
    NewsTypeId: 5,
    TypeName: '社会',
  },
  {
    NewsTypeId: 10,
    TypeName: '娱乐',
  },
  {
    NewsTypeId: 12,
    TypeName: '体育',
  },
  {
    NewsTypeId: 20,
    TypeName: 'NBA',
  },
  {
    NewsTypeId: 30,
    TypeName: 'CBA',
  },
  {
    NewsTypeId: 13,
    TypeName: '科技',
  },
  {
    NewsTypeId: 21,
    TypeName: 'VR',
  },
  {
    NewsTypeId: 23,
    TypeName: '移动',
  },
  {
    NewsTypeId: 26,
    TypeName: '足球',
  },
  {
    NewsTypeId: 27,
    TypeName: '军事',
  },
  {
    NewsTypeId: 34,
    TypeName: '财经',
  },
  {
    NewsTypeId: 18,
    TypeName: '旅游',
  },
  {
    NewsTypeId: 19,
    TypeName: '苹果',
  },
  {
    NewsTypeId: 31,
    TypeName: '游戏',
  },
  {
    NewsTypeId: 8,
    TypeName: '国际',
  },
  {
    NewsTypeId: 24,
    TypeName: '创业',
  }
]

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime,
  txapi_base_url: txapi_base_url, //暴露接口地址给其他文件使用
  txapi_key: txapi_key,           //暴露天行数据密匙
  NewsTypeList: NewsTypeList      //新闻类目
}


2,在项目目录pages/index下的index.js编写主要的逻辑代码

var util = require('../../utils/util.js')  //引用util.js文件
Page({
data: {
scrollHeight: 0,      //页面高度
currentID: 7,         //新闻类型
      TianAPInewsList: [],  //默认数据列表
scrollTop: 0,         //Y轴滚动条位置
touchXStart: 0,       //X轴开始位置
touchYStart: 0,       //Y轴开始位置
currentPage: 1,        //默认页数
},
onLoad: function () {
this.setData({ NewsTypeList: util.NewsTypeList });
this.loadNewslList(7);
wx.showShareMenu({
withShareTicket: true
})
},
initNewsData: function () {//初始化数据
this.setData({
scrollTop: 0,
TianAPInewsList: [],
currentPage: 1,
scrollHeight: 0
});
},
refreshNewList: function (e) {//获取最新数据
this.initNewsData();
this.loadNewslList(this.data.currentID);
},
loadMoreNews: function (e) {//加载更多新闻数据
this.setData({currentPage: this.data.currentPage + 1});
this.loadNewslList(this.data.currentID);
},
setCurrentYScroll: function (event) {//设置当前Y轴滚动条位置
this.setData({
scrollTop: event.detail.scrollTop
});
},
loadNewslList: function (NewsTypeId = "") {//加载新闻列表
let that = this;
wx.showLoading({title: '加载中...'})
wx.request({
url: util.txapi_base_url + '/allnews/',   //util中声明的接口地址
data: {
col: NewsTypeId,
key: util.txapi_key,         //util中声明的天行数据密匙apikey
page: that.data.currentPage,
num:10
},
success: function (res) {
let temp_data = res.data.newslist;
if (res.data.newslist.length != 0) {
that.setData({ TianAPInewsList: res.data.newslist.concat(temp_data) });
}
else {
that.setData({ TianAPInewsList: res.data.msg});
}
wx.getSystemInfo({//设置scroll内容高度
success: function (res) {
that.setData({
scrollHeight: res.windowHeight,
});
}
});
wx.hideLoading()  //关闭加载提示
}
})
},
handerTap: function (e) {//点击新闻分类
let that = this;
let tempList = this.data.NewsTypeList;
tempList.forEach(function (item, index) {
if (e.target.id == item.NewsTypeId) {
that.initNewsData();
that.setData({currentID: item.NewsTypeId});
that.loadNewslList(item.NewsTypeId);
}
});

},
handerNavigator: function (e) {//点击新闻列表跳转
wx.showModal({
title: '提示',
content: '小程序不支持外链,原文可用相应插件转换',
showCancel:false,
success: function (res) {
}
})
},
handerTouchStart: function (e) {//X,Y开始位置
let temp = [];
this.setData({touchXStart: e.changedTouches[0].clientX, touchYStart: e.changedTouches[0].clientY});
},
handerTouchEnd: function (e) {//判断左右滑动
let distanceX = this.data.touchXStart - e.changedTouches[0].clientX;
let distanceY = this.data.touchYStart - e.changedTouches[0].clientY;
let that = this;
let tempList = this.data.NewsTypeList;
let tempIndex = 0;
tempList.forEach(function (item, index) {
if (that.data.currentID == item.NewsTypeId) {
tempIndex = index;
}
});
if (Math.abs(distanceX) > Math.abs(distanceY) && distanceX < 0) {//左
if (tempIndex != 0) {//分类起点向左滑动
that.initNewsData();
that.setData({currentID: tempList[tempIndex - 1].NewsTypeId});
that.loadNewslList(tempList[tempIndex].NewsTypeId);
}
}
else if (Math.abs(distanceX) > Math.abs(distanceY) && distanceX > 0) {//右
if (tempIndex != tempList.length) {//分类终点向右滑动
that.initNewsData();
that.setData({currentID: tempList[tempIndex + 1].NewsTypeId});
that.loadNewslList(tempList[tempIndex].NewsTypeId);
}
}
}
});


3,在pages/index目录下的index.wxml中编写前端代码

<view class="page">
<view class="page__bd">
<scroll-view  scroll-x="true" class="scroll-view">
<view wx:for="{{NewsTypeList}}" id="{{item.NewsTypeId}}" wx:key="{{item.NewsTypeId}}" class="scroll-view-item {{currentID == item.NewsTypeId?'active':''}}" bindtap="handerTap">{{item.TypeName}}</view>
</scroll-view>

<view class="weui-panel weui-panel_access" style="margin:0" bindtouchstart="handerTouchStart" bindtouchend="handerTouchEnd">
<view class="weui-panel__bd">
<scroll-view  scroll-y="true" bindscrolltoupper="refreshNewsList" bindscrolltolower="loadMoreNews"
style="height: {{scrollHeight}}px;" scroll-top="{{scrollTop}}" bindscroll="setCurrentYScroll">
<view  class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active" wx:for="{{TianAPInewsList}}"
wx:key="{{index}}" bindtap="handerNavigator" data-index="{{index}}">
<view class="weui-media-box__bd weui-media-box__bd_in-appmsg">
<view class="weui-media-box__desc">{{item.title}}</view>
<view class="weui-media-box__info">
<view class="weui-media-box__info__meta">{{item.description}}</view>
<view class="weui-media-box__info__meta">{{item.ctime}}</view>
</view>
</view>
<view class="weui-media-box__hd weui-media-box__hd_in-appmsg">
<image class="weui-media-box__thumb" src="{{item.picUrl}}" />
</view>
</view>
</scroll-view>
</view>
</view>
</view>
</view>


4,在pages/index目录下的index.wxss编写小程序的样式代码

.scroll-view {
overflow: hidden;
width: 100%;
height: 50px;
line-height: 50px;
white-space:nowrap;
background: #00bbec;
color:#fff;
z-index: 3;
border-bottom: 1px solid #1db5fe;
}
.scroll-view-item {
display:inline-block;
margin:6px;
}
.scroll-view-item.active{
color:#cfdce2;
}

5,pages/index目录下的index.json是小程序配置文件,小程序中的页面文件(pages)的路径、窗口(window)表现等等配置项都可以在这里设置。例如:

"navigationBarBackgroundColor": "#00bbec",   //导航栏背景颜色
"navigationBarTitleText": "我的新闻头条",    //导航栏标题等


6,导入到微信web开发者工具后编译预览效果如下:


用天行数据API接口开发一个新闻微信小程序


以上就是这个新闻小程序项目的主要代码了,完整的项目代码可点击下面的附件下载。你只需要在在项目目录utils下的utils.js文件开头,把你在天行数据中注册得到的apikey填入txapi_key位置即可使用。

html5网页如何使用?批量替换wxml文件中的view布局为div,其他相应标签改为html代码,建议用后端的方式请求新闻数据接口以避免暴露key,wxml文件改为php,用file_get_contents或curl方式获取api接口的数据,用json_decode()解码,for或foreach遍历数组。具体的代码在天行数据官网代码示例中可找到。


TianApiNews.zip


本站所有文章均为天行博客原创,转载请注明来源及出处!

作者:宇天行 (关于我

本文首发地址:https://www.huceo.com/post/487.html

或许您还会喜欢这些文章:

Tags: 作者:宇天行 | 分类:开发技术 | 评论:8 | 浏览:6837

您正在以游客身份发表评论:

必填

选填

选填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。