sapui5 - 如何正确绑定异步。将数据从新闻 API 加载到视图并将数据显示为内容?
问题描述
我想在我的 SAPUI5 应用程序中从 News API ( https://newsapi.org/ ) 中获取数据,就像在这里完成的那样 ( https://www.nathanhand.co.uk/blog/post/creating-a-news-app- using-ui5 ),但没有 express 和 Node.js。获取过程本身有效,我从 API 中以 JSON 格式获取数据。问题似乎是 UI5 的生命周期,尤其是 API 数据的异步加载。我目前无法在我的视图中显示数据,因为它到达很晚,它似乎是用视图初始化的。
我尝试使用“attachRequestCompleted”事件处理程序,以确保数据在那里,并且只有在数据到达时才采取进一步的行动。但这并没有解决问题,数据正确绑定到视图,但似乎为时已晚。
return Controller.extend("newsapitest.newsapitest.controller.View1", {
onInit: function () {
var thisContext = this;
var articleModel = new JSONModel("https://newsapi.org/v2/top-headlines?country=DE&category=business&apiKey=*********");
articleModel.attachRequestCompleted(function(oEvt) {
var model = oEvt.getSource();
thisContext.getView().setModel(model, "articles");
});
}
});
<content>
<GenericTile backgroundImage="{articles>/1/urlToImage}"
frameType="TwoByOne" press="onArticlePress">
<TileContent footer="{articles>/1/publishedAt}">
<NewsContent contentText="{articles>/1/title}"
subheader="{articles>/1/description}" />
</TileContent>
</GenericTile>
</content>
因此,我期望视图中的图块将显示存储在模型中的每篇文章的信息。但目前只有一个空图块,那里没有显示任何数据。
解决方案 我在将模型绑定到我的控件时犯了一个错误。那是一个错误。我改变的另一件事是数据如何加载到我的模型中。
return Controller.extend("newsapitest.newsapitest.controller.View1", {
onInit: function () {
var articleModel = new JSONModel();
articleModel.loadData("https://newsapi.org/v2/top-headlines?country=DE&category=business&apiKey=37a02aae93684d58810e0b996954f534");
this.getView().setModel(articleModel);
},
});
<content>
<GenericTile
backgroundImage="{/articles/0/urlToImage}"
frameType="TwoByOne" press="onArticlePress">
<TileContent footer="{/articles/0/publishedAt}">
<NewsContent
contentText="{/articles/0/title}"
subheader="{/articles/0/description}" />
</TileContent>
</GenericTile>
</content>
解决方案
您是否检查过您的绑定路径是否正确?无论如何,您进行绑定的方式只会创建一个磁贴,其中的信息存储在文章数组的第二个位置(位置 1)。
如果要根据数组的位置数动态创建多个图块,我认为您不能使用“通用图块”组件,而是可以按如下方式使用“图块容器”(已弃用组件,但我认为没有其他方法可以这样做,至少在视图上):
<TileContainer
tiles="{articles>/}">
<StandardTile
title="{articles>title}"
info="{articles>publishedAt}"
infoState="{articles>description}" />
</TileContainer>
如果其他人知道不使用已弃用组件的方法来做到这一点,那就太好了:)。
推荐阅读
- python - 如何在数据框python中创建具有特定数字的空列?
- android - Android/Kotlin onClick 从一个片段
- php - 如何使用 sprintf 函数添加 Html 标签
- docker - 如何使用 docker-nginx-certbot 创建我的域(包括 www)的 SSL 证书?
- java - Java执行过滤器和分组并使用2个列表执行媒体
- c++ - 打开 Gnome 终端选项卡,在 Ubuntu 18.04 LTS 上使用 C++ 运行命令
- javascript - 如何使我的 html 网站中的图片可点击?
- python - 检查每个偶数索引是否包含偶数并且每个奇数索引是否包含给定列表的奇数的程序存在问题
- symbolicc++ - 尝试将此数据类型包含在另一个头文件中时出现冲突类型错误我不确定为什么
- php - 与 if 语句相比,switch 语句如何加载?