自從上次發布新聞頭條小程序后,經常會有同學問點擊新聞標題后為什么會提示“小程序不支持外鏈,原文可用相應插件轉換”。這是因為新聞接口的數據源來自各大新聞平臺,而微信小程序是不允許打開非業余域名內的鏈接的,所以應該在得到新聞url鏈接后,通過html轉wxml插件將獲取到的html網頁文件轉為支持小程序顯示的wxml組件結構。
但是對編程經驗不多的小伙伴來說微信小程序顯示外鏈微信小程序顯示外鏈,有一定難度。且轉換過程對復雜網頁結構并不太友好。其實是可以利用天行數據的“新聞全文”接口,來直接獲取網頁(包含網頁圖片等富媒體)的全文數據的,具體的演示效果如下。
(新聞全文)
(新聞列表)
視頻效果演示,下載了上個版本的新聞頭條小程序可以重新下載新版本,解壓覆蓋即可,如果有自定義修改的地方,請注意備份。
主要修改了以下幾個地方,打開pages/index/index.js第90行位置,將原來提示需要插件轉換的地方,改為跳轉事件,前端綁定傳遞一個新聞url數據給跳轉后的view頁面。
handerNavigator: function (e) {//點擊新聞列表跳轉
var url = e.currentTarget.dataset.url // 新聞url
wx.navigateTo({
url: '/pages/view/view?url=' + url
});
},
在pages目錄下新建view/view.js、view.wxml、view.wxss、view.json文件,打開view.js文件復制粘貼以下代碼:
var util = require('../../utils/util.js')
Page({
data: {
},
onLoad: function (options) {
this.loadNewsContent(options.url);
wx.showShareMenu({
withShareTicket: true
})
},
loadNewsContent: function (url) {//加載新聞內容
let that = this;
wx.showLoading({title: '加載中...'})
wx.request({
url: util.txapi_base_url + '/txapi/htmltext/',
data: {
key: util.txapi_key,
url: url
},
success: function (res) {
if (res.data.code == 200) {
wx.setNavigationBarTitle({
title: res.data.newslist[0].title
????????????????})
that.setData({
TianAPInewsTitle: res.data.newslist[0].title,
TianAPInewsContent: res.data.newslist[0].content,
TianAPInewsContentTime: res.data.newslist[0].ctime
});
}
else {
wx.showModal({
title: '天行數據',
content: res.data.msg + '\n錯誤狀態碼:' + res.data.code,
showCancel: false,
success: function (res) {
wx.navigateBack()
}
})
}
wx.hideLoading() //關閉加載提示
}
})
}
});
在view.wxml復制粘貼以下代碼:
class ="NewsContent"><view class="title">{{TianAPInewsTitle}}view>
{{TianAPInewsContentTime}}
class ="content" nodes="{{TianAPInewsContent}}">rich-text>view>
另外還要注意在根目錄的app.json中增加新的頁面路由:
"pages": [
"pages/index/index",
"pages/view/view"
],
通過以上修改,你的新聞頭條小程序就支持顯示新聞原文了,如果提示“320錯誤,API沒有調用權限”,請自行登錄天行數據完成權限的升級開通。
下載新的新聞小程序代碼,請點擊閱讀原文。如何使用代碼,請參數下面的文章。